This is a bit of a silly question, but if I want to add an object to an array I can do it with both NSMutableArray
and NSArray
, which should I use?
Even the Q and the answer are very old, someone has to correct it.
If you are talking about performance, you can measure it yourself. But remember Donald Knuth: "Premature optimization is the root of all evil".
On an architectural point of view, things become more complicated.
First of all I have to mention, that having an instance of NSArray
does not mean, that it is immutable. This is, because in Cocoa the mutable variants of collections are subclasses of the immutable variants. Therefore an instance of NSMutableArray
is an instance of NSArray
, but obviously mutable.
One can say that this was no good idea, especially when thinking about Barbara and Jeanette and there is a relation to the circle-ellipse problem, which is not easy to solve. However, it is as it is.
So only the docs can give you the information, whether a returned instance is immutable or not. Or you do a runtime check. For this reason, some people always do a -copy
on every mutable collection.
However, mutability is another root of all evil. Therefore: If it is possible, always create an instance of NSArray
as final result. Write that in your docs, if you return that instance from a method (esp. getter) or not, so everyone can rely on immutability or not. This prevents unexpected changes "behind the scene". This is important, not 0.000000000003 sec runtime or 130 bytes of memory.