1

Given the following class def:

@interface MyController : OtherController {
    NSString *_ID;
}
@property(nonatomic,retain) NSString *ID;
@end

and the following implementation:

@implementation DRMControllerNDS
@synthesize ID =_ID;
@end

What is the @synthesize statement doing here? Specifically why are we are setting the _ID instance variable value to the ID property? Isn't _ID going to be nil at this point in execution? I have seen this construct used many times and am yet to understand its purpose...

Can anyone explain this?

Sabobin
  • 4,256
  • 4
  • 27
  • 33
  • It's a convention to distinguish between direct access to the variable (_var), and access through the synthesized accessors (self.var). – Jano Sep 16 '11 at 10:50
  • Similar questions: [1](http://stackoverflow.com/questions/3802851/objective-c-synthesize-property-name-overriding), [2](http://stackoverflow.com/questions/3277209/can-someone-explain-this-synthesize-syntax), [3](http://stackoverflow.com/questions/6112283/question-about-synthesize/6112553), [4](http://stackoverflow.com/questions/3802851), [5](http://stackoverflow.com/questions/382051), [6](http://stackoverflow.com/questions/3266467), [7](http://stackoverflow.com/questions/5170631), [8](http://stackoverflow.com/questions/3277209), [9](http://stackoverflow.com/questions/719788) – Jano Sep 16 '11 at 10:51
  • @Sabobin: Each of those numbers is a link. – Peter Hosey Sep 16 '11 at 19:43
  • Oh, my mistake sorry guys. :) – Sabobin Sep 19 '11 at 11:45

2 Answers2

4

In plain English, the @synthesize line says "Create the getter and setter methods for the property "ID", but don't use an instance variable called "ID" (the default) to store the value, use an instance variable called "_ID" instead."

Johannes Fahrenkrug
  • 42,912
  • 19
  • 126
  • 165
0

If you tried to access instanceOfMyController._ID, you'll get an error because the ._ID property doesn't exist; the @synthesize directive allows you to use the dot notation.

See this question for more.

Community
  • 1
  • 1
Alex
  • 9,313
  • 1
  • 39
  • 44
  • The `_ID` property still doesn't exist; no such property has been declared. The property is `ID`, and this `@synthesize` directive tells the compiler to use the `_ID` instance variable for the `ID` property's storage. – Peter Hosey Sep 16 '11 at 19:45
  • So is the goal to allow you to use the dot notation or use the instance variable name, but keep them separate for some reason? It's still not clear. In other words, can I write: instanceOfMyController.ID OR _ID to access the variable? Or am I restricted to one or the other? – Elisabeth May 13 '12 at 17:48
  • Oh, just thought of something: is using _ID a way to get around using getters and setters? That is, if I use instanceOfMyController.ID I am using the setter/getter, but if I use _ID, I'm not? – Elisabeth May 13 '12 at 17:50