objective-c – When should synthesize be used?

Question:

Could you explain in simple terms in what situations synthesize is needed? As I understand it, it makes it possible to access properties through get- and set-. It turns out that a property without synthesize is no different from a class variable? And does it make sense then to write songs without synthesize?

Answer:

Properties (property) appeared in Objective-C only in version 2.0, and they are reduced to ordinary methods (or messages, if you like). That is, if you declare a property

@property (nonatomic, retain) NSString* property1;

then you are actually declaring a getter and setter like this:

-(NSString*)property1;
-(void)setProperty1:(NSString*)value;

When you use property

NSString* p = v.property1;
v.property1 = p;

in fact, the compiler "expands" this into code like this:

NSString* p = [v property1];
[v setProperty1:p];

@synthesize property1; expands into code definitions for the setter and getter (according to the parameters you provided in the property declaration). You don't have to write @synthesize , but in that case you have to write the getter and setter implementations yourself. If you do neither, the compiler will issue a warning and code that uses the property will crash.

Since @property expands into setter and getter declarations , it must be written in the class interface (usually in a header file – .h). Similarly, @synthesize "generates" setter and getter implementations , so it is used in the implementation file (.m, .mm).

Scroll to Top