Mutable vs Immutable Objects

A mutable object can be changed after it's created, and an immutable object can't.

In Objective-C, mutable types, like NSMutableArray, can be modified:

NSMutableArray *mutableArray = @[@4, @9]; mutableArray[0] = @1; // mutableArray is now @[@1, @9]

Immutable types, like NSArray, can't be changed:

NSArray *immutableArray = @[@4, @9]; immutableArray[0] = @1; // doesn't compile

Strings are the same way. Use NSMutableString for mutable strings, and NSString for immutable strings:

NSMutableString *mutableString = [NSMutableString stringWithString:@"Hello, world"]; [mutableString appendString:@"!"]; // mutableString is now @"Hello, world!"
NSString *immutableString = @"Hello, world!"; // No methods exist to modify immutableString on the NSString interface

Mutable objects are nice because you can make changes in-place, without allocating a new object. But be careful—whenever you make an in-place change to an object, all references to that object will now reflect the change.

What's next?

If you're ready to start applying these concepts to some problems, check out our mock coding interview questions.

They mimic a real interview by offering hints when you're stuck or you're missing an optimization.

Try some questions now

. . .