I thought I understood @property and @synthesize, but I did some experimenting and I can't figure out why the below (what I thought was broken) code works.
As you can see, there's no instance variable that corresponds to the name property. Does Objective-C somehow create an instance variable if it doesn't find an instance variable with the same name and type?
Header:
#import <Foundation/Foundation.h> @interface AddressCard : NSObject { } @property (copy, nonatomic) NSString *name; -(void) print; @end
Implementation:
#import "AddressCard.h" @implementation AddressCard @synthesize name; -(void) print { NSLog(@"Name=%@", self.name); } -(void) dealloc { [name release]; [super dealloc]; } @end
Test:
int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; AddressCard *ac = [[AddressCard alloc] init]; ac.name = @"Brandon"; [ac print]; [ac release]; [pool drain]; return 0; }
A property can be backed by an instance variable, but you can also define the getter/setter to do something a bit more dynamic, e.g. you might define a lowerCase property on a string which dynamically creates the result rather than returning the value of some member variable.
In objective c, a property is an instance variable which can take advantage of an overloaded dot operator to call its setter and getter.
Default Synthesis Of Properties Clang provides support for autosynthesis of declared properties. Using this feature, clang provides default synthesis of those properties not declared @dynamic and not having user provided backing getter and setter methods.
@synthesize tells the compiler to take care of the accessor methods creation i.e it will generate the methods based on property description. It will also generate an instance variable to be used which you can specify as above, as a convention it starts with _(underscore)+propertyName.
The quick answer is: "yes". In Objective-C 2.0, synthesized properties will automatically create the corresponding ivars as required.
Apple's documentation has some more details.
Important: As pointed out by Tommy (note: this is from the legacy docs - please see the latest information):
In Objective-C 2.0 on either of the modern runtimes (ie, Intel 64bit and ARM) properties can be added to classes 'dynamically' (that is, at runtime but only before the creation of any instances — not particularly dynamic compared to the rest of the runtime). However, this can't be done on either of the two older runtimes (ie, Intel 32bit and PowerPC). It's therefore not really something you want to use on shipping software for the Mac or during development for iOS (since the simulator is a 32bit Intel application and can't create instance variables at runtime)
You can omit instance variable declaration only for 64-bit architecture
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With