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;
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…