views:

782

answers:

3

What is the difference between these two?

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

What is the other type like this?

+4  A: 

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

Chris Long
Should these methods be named setMyObject?
gerry3
Good catch. `@property` has spoiled me! Editing...
Chris Long
Also, the other "type like this" is "assign" which is used to copy primitive types (e.g. int, float, BOOL).
gerry3
If you would implement a retaining setter by hand, the one you described is not the way to do it. You should first check the "old" field value and release it if it still has a value. But only do this if the old value is different than the value you're trying to set. Everntually you will have a 4 to 5 line code setter. Once you see that, you will appreciate the @property notation even more! :)
Tom van Zummeren
A: 

As a general rule, use:

@property(nonatomic, copy)

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

@property(nonatomic, retain)
Andrew Ebling
Actually, since NSString is immutable won't it make more sense to simply use @property (nonatomic, retain) for NSString? Maybe you mean the other way around.
futureelite7
I think the idea is to make a copy in case the string is actually a mutable string. That way the string won't unexpectedly change on you.
Nimrod