开发者

@synthesize in Objective-c?

开发者_开发问答test.h

NSString *name;
@property(nonatomic,retain) NSString *name;

test.m

@synthesize name;

here why did we use nonatomic , retain in the property and in .m file why we are using @synthesize ?

please answer ,


Apple Documentation

nonatomic is described in detail here.

retain means that the property is retained when the value is set to anything other than nil. There are other options such as copy and assign. Normally object types that can be copied should use copy, like NSString. assign simply sets the pointer value.

@synthesize stubs out the getter and setter methods for the property and is required in order for the nonatomic and retain to work.

Also, make sure that if you use retain or copy, that you also release the object in the dealloc method.

- (void)dealloc {
    [name release];
    [super dealloc];
}


The nonatomic means that setting the property is not thread-safe, retain means new value is retained (and the old value released), and the @synthesize actually creates the methods that are necessary for the property. In this case, it evaluates to something like this:

- (NSString *)name {
    // Method "name", returning content of variable "name".
    return name;
}

- (void)setName:(NSString *)newName {
    [newName retain];
    [name release];
    name = newName;
    // Also some magic for KVO is added here.
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜