objective-cpropertiessynthesize

@synthesize behind the scenes


When we create a property and defined a synthesize for it, the compiler automatically creates getters and setters methods, right?

Now, If I execute this command:

@property(nonatomic) int value;

@synthesize value;

value = 50;

What happens:

The compiler saves the value '50' in the property?

property (nonatomic) int value; // Here is the stored value 50!

or the compiler creates a variable behind the scenes with the same name of the property like this:

interface myClass: NSObject {
    int value; // Here is the stored value 50!
}

What actually happens and what the alternatives listed above is correct?


Solution

  • It's probably semantics, but @synthesize is no longer required for properties. The compiler does it automatically.

    But to answer your question, the compiler creates an instance variable to store the value for the property.

    @property (nonatomic, assign) NSInteger value;
    // an instance variable NSInteger _value; will be created in the interface.
    

    You can use the instance variable in your own code if you need to access it without going through the property. This is common when overriding a setter, like so:

    - (void)setValue:(NSInteger)value {
        _value = value;
        // custom code
    }