Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
342 views
in Technique[技术] by (71.8m points)

objective c - Synthesizing a property without instance variables

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...