3

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?

Thomas Joulin
  • 6,590
  • 9
  • 53
  • 88
moon6pence
  • 712
  • 9
  • 24

2 Answers2

5

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.

JeremyP
  • 84,577
  • 15
  • 123
  • 161
  • 1
    +1 Most of the time just use copy, as someone might feed you with a mutable object that might change behind your back, so the code is likely to not work as expected anyway. I'd only consider retain if you a) know all of the code really well and b) identified (measured!) a bottle neck. – Eiko Jul 05 '11 at 10:21
-1

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.

Gobra
  • 4,263
  • 2
  • 15
  • 20
  • 3
    No, immutable objects implementing `NSCopying` should be copied. The reason is that although an object might be advertised as immutable, underneath it might not be. – JeremyP Jul 05 '11 at 08:21