Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSArray property: copy or retain?

Tags:

According to this: NSString property: copy or retain?

For NSString/NSMutableString, copy is recommended.

How about NSArray/NSMutableArray?

like image 999
Howard Avatar asked May 01 '11 17:05

Howard


People also ask

What is difference between NSArray and NSMutableArray?

The primary difference between NSArray and NSMutableArray is that a mutable array can be changed/modified after it has been allocated and initialized, whereas an immutable array, NSArray , cannot.

Can NSArray contain nil?

arrays can't contain nil.

Is NSArray ordered?

The answer is yes, the order of the elements of an array will be maintained - because an array is an ordered collection of items, just like a string is an ordered sequence of characters...

How do you declare NSArray in Objective C?

In Objective-C, the compiler generates code that makes an underlying call to the init(objects:count:) method. id objects[] = { someObject, @"Hello, World!", @42 }; NSUInteger count = sizeof(objects) / sizeof(id); NSArray *array = [NSArray arrayWithObjects:objects count:count];


2 Answers

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.

like image 50
Caleb Avatar answered Oct 14 '22 09:10

Caleb


choose copy, unless you have a very specific reason not to, as well as all the supporting code/interface to back that up.

i detailed the rationale and several implications here: NSMutableString as retain/copy

that example is based on NSStrings, but the same applies for NSArrays.

like image 38
justin Avatar answered Oct 14 '22 08:10

justin