Reputation: 712
if object has property of type NSString
or NSNumber
, which is better, retain
or copy
?
I think these objects are immutable, (can not change state of object) so copy is better?
I see the example why copy is better that assign NSMutableString and change it, but there's no NSMutableNumber
. Then in the case of NSNumber
, I'd better use retain
to NSNumber
objects?
If copy
is better because NSString
and NSNumber
has small memory usage, how about if property is NSArray
type?
NSArray
type is also immutable, what about use copy in NSArray
properties?
Upvotes: 3
Views: 1911
Reputation: 86651
With immutable objects, copy.
For immutable objects like most NSStrings, -copyWithZone:
is effectively
-(id) copyWithZone: (NSZone*) zone
{
return [self retain];
}
so the overhead is minimal.
With mutable objects, probably copy but with large mutable objects like strings and large mutable arrays, you need to make a judgement call based on profiling your code. Also, of course, with mutable objects you might want the original because you might want to see the changes in the original.
Upvotes: 5
Reputation: 4261
Why can you be interested in copying an immutable object? Actually, immutable classes could simply return [self retain]
inside the copy method. What I usually do:
Of course, the rules above are not absolute, but in general they work.
Upvotes: -1