0

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?

Sulthan
  • 128,090
  • 22
  • 218
  • 270
LettersBa
  • 747
  • 1
  • 8
  • 27
  • 1
    I don't see why it would create a variable behind the scenes, but I have no idea really. Why do you ask? – notadam Mar 17 '15 at 14:49
  • @adam10603 I asked this sort of thing, because I'm starting to learn about dynamic, and setting a property dynamic you have to do this manually, now that already know how works synthesize, already have a better idea of how the dynamic works. – LettersBa Mar 17 '15 at 15:01

1 Answers1

4

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
}
Jasarien
  • 58,279
  • 31
  • 157
  • 188
  • @property generates the instance variable and the setter and getter methods, not a bridge. When you access a property like `object.property;` the compiler translates it to `[object property];` or `object.property = value;` into `[object setProperty:value];` - it's more of a syntactic short cut than a bridge. – Jasarien Mar 17 '15 at 15:04
  • To extend on you answer, the `@synthesize` call can actually set the name of the ivar, e.g. `@synthesize x = myX`. The important thing to understand is that the property is a setter and a getter, 2 methods. A property doesn't have to have an ivar at all. – Sulthan Mar 17 '15 at 15:38
  • This is true, and it can be tricky to know which cases will generate an ivar and which won't. This answer has a pretty good summary http://stackoverflow.com/questions/12933785/ios-automatic-synthesize-without-creating-an-ivar – Jasarien Mar 17 '15 at 15:41