开发者

iphone @property

What is the difference between th开发者_运维知识库ese two?

@property (nonatomic, retain)
@property (nonatomic, copy)

What is the other type like this?


http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocProperties.html#//apple_ref/doc/uid/TP30001163-CH17-SW27


Using retain is equivalent to this method:

- (void)setMyObject:(id)object {
    myObject = [object retain];
}

Using copy is like this:

- (void)setMyObject:(id)object {
    myObject = [object copy];
}

The main difference is that there are now two copies of the same object. Now, if you change an instance variable in your class (such as changing @"A" to @"B"), the original object will stay intact (it will still be @"A").


As a general rule, use:

@property(nonatomic, copy)

..for NSString properties and this for all other object properties:

@property(nonatomic, retain)


For attributes whose type is an immutable value class that conforms to the NSCopying protocol, you almost always should specify **

copy

** in your @property declaration. Specifying **

retain

** is something you almost never want in such a situation.

Since in almost all cases you want to prevent mutating an object's attributes behind its back, you should mark the properties representing them copy. (And if you write the setter yourself instead of using @synthesize you should remember to actually use copy instead of retain in it.)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜