moon6pence
moon6pence

Reputation: 712

in NSString, NSNumber type property, which is better: retain or copy? (and how about NSArray?)

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

Answers (2)

JeremyP
JeremyP

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

Gobra
Gobra

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:

  • Assign for UI outlets and in some other specific references where it's important to avoid retain cycle
  • Simply retain immutable objects
  • Copy simple mutable object
  • Deep copy for the container types (mutable arrays, dictionaries etc.)

Of course, the rules above are not absolute, but in general they work.

Upvotes: -1

Related Questions