Why do common collection classes in Objective C like NSString, NSArray, NSDictionary etc have a mutable as well as an immutable version. What is the logic behind defining them s
Why do common collection classes in Objective C like NSString, NSArray, NSDictionary etc have a mutable as well as an immutable version.
the concept is used in related langauges. the notable distinction is that the objc types are named mutable variants. similar langauges typically accomplish this via application of a keyword, such as const
. of course, other related languages also use types which are explicitly mutable or immutable.
What is the logic behind defining them separately?
objc messaging does not distinguish const and non-const, and the language does not provide builtin support for ensuring an object's state does not change (although it really would not be a difficult addition if one were really inclined to extend a compiler). so there's a little bit of history involved here too.
therefore, it's convention for the class to define immutability vs mutability, and to supply variants which distinguish mutability.
multiple abstractions also introduce type safety and intention.
Performance
yes. there are multiple optimizations an invariant object can make.
some cases include:
memory management
some cases include:
copyWithZone:
or initWithType:
could return the source retained, rather than a deeep or shallow physical copy.or anything else?
it makes it easier to write clear interfaces. you can guarantee and (attempt to) restrict some things. if everything were mutable, there would be many more mistakes to make and special cases. in fact, the distinction could entirely change the way we approach writing objc libraries:
[[textField stringValue] appendString:@" Hz"];
[textField stateDidChange];
so it's nice to be able to pass objects around without worrying that the client will change behind your back, while avoiding copying all over the place.