jaleel
jaleel

Reputation: 307

iphone @property

What is the difference between these two?

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

What is the other type like this?

Upvotes: 2

Views: 4090

Answers (4)

iOS dev
iOS dev

Reputation: 2284

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.)

Upvotes: 0

Andrew Ebling
Andrew Ebling

Reputation: 10283

As a general rule, use:

@property(nonatomic, copy)

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

@property(nonatomic, retain)

Upvotes: 0

Chris Long
Chris Long

Reputation: 3074

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").

Upvotes: 6

Related Questions