NSMutableString
NSMutableString is the mutable subclass of NSString. It has every NSString method plus methods that change the string in place. Use it when you build text piece by piece, for example in a loop.
Creating and appending
#import <Foundation/Foundation.h>
int main(void) {
@autoreleasepool {
NSMutableString *report = [NSMutableString string]; // empty
[report appendString:@"Daily report"];
[report appendString:@"\n"];
[report appendFormat:@"Visitors: %d\n", 128];
[report appendFormat:@"Bounce rate: %.1f%%", 37.4];
NSLog(@"%@", report);
NSMutableString *name = [NSMutableString stringWithString:@"Ada"];
[name appendString:@" Lovelace"];
NSLog(@"%@ (%lu characters)", name, (unsigned long)name.length);
}
return 0;
}Daily report
Visitors: 128
Bounce rate: 37.4%
Ada Lovelace (12 characters)
Note that @"…" literals are always immutable. To get a mutable string you must create one with [NSMutableString string], stringWithString:, stringWithCapacity: or mutableCopy.
Inserting, deleting and replacing
#import <Foundation/Foundation.h>
int main(void) {
@autoreleasepool {
NSMutableString *s = [NSMutableString stringWithString:@"Hello world"];
[s insertString:@"big " atIndex:6];
NSLog(@"insert: %@", s);
[s deleteCharactersInRange:NSMakeRange(0, 6)];
NSLog(@"delete: %@", s);
[s replaceCharactersInRange:NSMakeRange(0, 3) withString:@"small"];
NSLog(@"replace: %@", s);
NSUInteger changed = [s replaceOccurrencesOfString:@"l"
withString:@"L"
options:0
range:NSMakeRange(0, s.length)];
NSLog(@"replaced %lu: %@", (unsigned long)changed, s);
[s setString:@"reset"];
NSLog(@"setString: %@", s);
}
return 0;
}insert: Hello big world
delete: big world
replace: small world
replaced 3: smaLL worLd
setString: reset
Building strings in a loop
A mutable string avoids creating a new object for every step:
#import <Foundation/Foundation.h>
int main(void) {
@autoreleasepool {
NSArray *items = @[@"bread", @"milk", @"eggs", @"apples"];
NSMutableString *list = [NSMutableString stringWithCapacity:64];
for (NSUInteger i = 0; i < items.count; i++) {
if (i > 0) {
[list appendString:@", "];
}
[list appendFormat:@"%lu. %@", (unsigned long)(i + 1), items[i]];
}
NSLog(@"Shopping: %@", list);
// A simple text bar chart
int sales[] = {3, 7, 5};
NSArray *days = @[@"Mon", @"Tue", @"Wed"];
for (int d = 0; d < 3; d++) {
NSMutableString *bar = [NSMutableString string];
for (int k = 0; k < sales[d]; k++) {
[bar appendString:@"#"];
}
NSLog(@"%@ %@ %d", days[d], bar, sales[d]);
}
}
return 0;
}Shopping: 1. bread, 2. milk, 3. eggs, 4. apples
Mon ### 3
Tue ####### 7
Wed ##### 5
stringWithCapacity: is only a hint about the expected size; the string still grows as needed.
mutableCopy and copy
mutableCopy turns any string into a new mutable one; copy turns a mutable string into an immutable snapshot:
#import <Foundation/Foundation.h>
int main(void) {
@autoreleasepool {
NSString *original = @"draft";
NSMutableString *editable = [original mutableCopy];
[editable appendString:@" v2"];
NSString *snapshot = [editable copy]; // immutable copy
[editable appendString:@" (edited)"];
NSLog(@"original: %@", original);
NSLog(@"editable: %@", editable);
NSLog(@"snapshot: %@", snapshot);
}
return 0;
}original: draft
editable: draft v2 (edited)
snapshot: draft v2
The same copy / mutableCopy pair exists for arrays, dictionaries, sets and data.
Mutable vs immutable
NSString |
NSMutableString |
|
|---|---|---|
| Change in place | no | yes |
| Safe to share between objects | yes | risky: others may change it |
| Created from a literal | yes | no |
| Typical use | properties, keys, return values | building text, then copy |
Tip: A common pattern is to build text with an
NSMutableStringinside a method and return it as anNSString(often with[result copy]), so callers can't modify your internal state.
Common mistake: mutating a literal
Casting an immutable string to NSMutableString * doesn't make it mutable. The compiler accepts the cast, but sending appendString: to an immutable string raises an exception at run time. Always create a real mutable string.
Test yourself
How do you get a mutable version of an existing NSString s?
- (NSMutableString *)s
- [s mutableCopy]
- [s copy]
- @mutable(s)
Which method adds formatted text to the end of a mutable string?
- stringByAppendingFormat:
- appendFormat:
- addFormat:
- insertFormat:
Is @"literal" a mutable string?
- Yes
- No, literals are always immutable NSStrings
- Only inside @autoreleasepool
- Only if assigned to an NSMutableString * variable