NSArray property: copy or retain?

Howard picture Howard · May 1, 2011 · Viewed 12.8k times · Source

According to this: NSString property: copy or retain?

For NSString/NSMutableString, copy is recommended.

How about NSArray/NSMutableArray?

Answer

Caleb picture Caleb · May 1, 2011

Since you're asking about NSArray (rather than NSMutableArray), you should use copy. NSArray is immutable, so you don't expect a property of that type to change. But NSMutableArray is a subclass of NSArray, so it's perfectly valid for someone to pass in a NSMutableArray. If you just retain that object, then it may change right under your nose. If you copy rather than retain, then the object won't change.

However, you should be aware that when you copy a container like NSArray, you're copying the container only and not its contents. If the array contains mutable objects, the contents of those objects may change even though the array itself is immutable.