Mutable Versus Immutable

While looking at NSString, you may have noticed that the content of the string is never modified directly. If you've checked out the NSArray class, you might be concerned that there doesn't appear to be any way to add or remove items to the array. Don't worry; the folks who designed Cocoa weren't that lazy!

Many of the classes for managing data are broken in two: one class to manage the data that never changes and a subclass for the part that can change. If the class name for the constant data is NSString, the class name NSMutableString is used for the one that can be modified.

Why use two classes when they could have just implemented one? For the same reason that constant values in other code are a good thing: You know that the data is never going to change as it's processed. You can make assumptions that you wouldn't have otherwise made.

Note

If you've ever had an array's size change as you're iterating over its elements, you know the pain of the bugs that these bad assumptions can incur.

When you're building your own classes, you'll often have to choose which of these two variants to use for your instance variables. A good rule of thumb is to use an immutable object like NSString or NSNumber when the value is replaced entirely. When you were making awesome strings, there would have been no point in using an NSMutableString since the –setOriginalString: method updated the whole string rather than making changes to individual characters.

Collections, on the other ...

Get iPhone App Development: The Missing Manual now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.