Thanks
Thanks

Reputation: 40359

Are there any reasons why I should prefer an NSArray instead of NSMutableArray?

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?

Upvotes: 1

Views: 225

Answers (3)

Rog
Rog

Reputation: 17170

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

Upvotes: 2

mouviciel
mouviciel

Reputation: 67919

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.

Upvotes: 2

1800 INFORMATION
1800 INFORMATION

Reputation: 135463

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.

Upvotes: 6

Related Questions