Let's say I have a class called SomeClass
with a string
property name:
@interface SomeClass : NSObject
{
NSString* name;
}
@property (nonatomic, retain) NSString* name;
@end
I understand that name may be assigned a NSMutableString
in which case this may lead to errant behavior.
- For strings in general, is it always a good idea to use the
copy
attribute instead ofretain
? - Is a "copied" property in any way less efficient than such a "retain-ed" property?
Best Answer
For attributes whose type is an immutable value class that conforms to the
NSCopying
protocol, you almost always should specifycopy
in your@property
declaration. Specifyingretain
is something you almost never want in such a situation.Here's why you want to do that:
The current value of the
Person.name
property will be different depending on whether the property is declaredretain
orcopy
— it will be@"Debajit"
if the property is markedretain
, but@"Chris"
if the property is markedcopy
.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 usecopy
instead ofretain
in it.)