views:

170

answers:

3

I feel that when I use NSArray, I might constraint myself some time in future. Are there any good reasons to prefer this "primitive" one instead of the "complex" one, which is mutable?

+6  A: 

Using a non-mutable structure in your code is not much of a constraint - if it turns out that you need to modify it later on you can change to use a mutable one. It can be more of a constraint if you have it in an external interface mind you. The main advantages of non-mutable is that you gain thread safety and it is more easy to conceptualize the code - there is less to concern you if mutability is taken out of the equation. This is why we have const constraints and so on - if you don't have to modify the data it is better to say so up front.

1800 INFORMATION
Exactly. Making it non-mutable enforces your interface contract.
Airsource Ltd
Also, NSMutableArray is marginally slower than NSArray. If you need speed, go with NSArray or a manually managed C-array.
rpetrich
+2  A: 

One reason is the YAGNI principle. If you don't need a mutable array, don't use it. So your code will be easier to understand, test and maintain.

Remember that code is not only processed by a compiler but also read by coders or testers. Using NSMutableArray instead of NSArray has a meaning for them. It may be counterproductive to give them false information about your intentions.

mouviciel
+2  A: 

In addition to the answers from Mssrs INFORMATION and mouviciel NSArray is faster than NSMutableArray. This is true for all the stati/mutable collections.

Roger Nolan