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 separately? Performance, memory management or anything else?
You may think of it as the object's address in memory. An object's type defines the possible values and operations. Objects whose value can change are said to be mutable. Objects whose value is unchangeable once they are created are called immutable.
An NSDictionary will retain it's objects, and copy it's keys.
In Swift, a variable is mutable whereas a constant is immutable. Xcode suggests turning the numberOfWheels constant into a variable by replacing the let keyword with the var keyword. In other words, Xcode suggests making numberOfWheels mutable. The value stored in a variable can be changed.
The main advantage of immutable objects is to make the concurrent programming. so if any application uses so many threads then we can use immutability. Re, "creating a new copy of the object for every single change can be very costly." Yup.
The immutable versions of the classes exist because an immutable object is, in and of itself, a unique identifier for a particular state. I.e. if you have an NSArray
of 100 NSString
instances, that NSArray
instance can be treated as idempotent for any one of those strings.
As well, the immutability means that a change cannot happen after the state has been vended. For example, NSView
's subviews
method returns an immutable array, thus ensuring that the caller isn't going to play games with the contents (nor even expect to be able to). Internally, NSView
could choose to return the [likely] NSMutableArray that contains the subviews (since it is internally mutable) and the typecast to NSArray
means the caller can't manipulate the contents without an evil cast or bad compiler warning. (This may or may not actually be the real implementation, btw -- but this pattern is used elsewhere).
Immutability also means that enumeration and/or traversal can be done without risk of a state change in the middle. Similarly, many immutable classes are also explicitly thread safe; any number of threads can simultaneously read the immutable state, often without need for a lock.
In general for an API, an immutable class is going to be thread safe so you can read it directly in a background thread without worrying the contents will change...
That matters more for things like a collection where contents can shift and you might be in the middle of enumerating them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With