Simple question I can’t seem to find a fast post for;
if I have an object, lets say:
NSString *myString_;
@property(readwrite, retain)NSString* myString;
@synthesize myString = myString_;
When I synthesize this, does this alloc memory for the object?
Thanks
All that @synthesize does is generate the accessors (setter and getter) for your property and create an instance variable with the same name. The added step of using the equals sign:
… renames the instance variable for you to _string (or whatever name you choose, the underbar is just an apple convention). This is good practice since having the instance variable share the same name as the accessors can be problematic. Having the underbar lets you differentiate between the two.
This is basically what is generated (assume ARC is ON):
and
You can initialize you property in an init method (using self.propertyName):
or you can initialize it lazily by overriding the getter like so:
Also note you don’t need to declare your variable separately (i.e. you don’t need NSString* mystring). Just use strong or weak in place of retain when declaring the property.
The only places you should access the instance variable directly is in the accessors, this allows you to control all action to it through a single gateway. The overhead of using the accessors within the class (i.e self.mystring) is infinitesimal. Of course you don’t have to do it this way, but it’s good practice.