Mutable collections in Objective-C
The mutable classes subclass the immutable ones and add writers.
#import <Foundation/Foundation.h>
int main(void) {
@autoreleasepool {
// Mutable classes subclass the immutable ones and add writers.
NSMutableArray<NSString *> *wants =
[@[ @"Blue Train", @"Nefertiti" ] mutableCopy];
[wants addObject:@"Speak No Evil"];
[wants removeObject:@"Nefertiti"];
NSLog(@"Want list: %@", [wants componentsJoinedByString:@", "]);
NSMutableDictionary<NSString *, NSNumber *> *prices =
[[NSMutableDictionary alloc] init];
prices[@"Blue Train"] = @29;
prices[@"Speak No Evil"] = @24;
[prices removeObjectForKey:@"Blue Train"];
NSLog(@"Priced titles: %lu", (unsigned long)[prices count]);
}
return 0;
}
How it works
mutableCopyturns a literal into something editable.addObject:andremoveObject:reshape the array.- Subscript assignment writes into a mutable dictionary.
Keywords and builtins used here
NSMutableArrayNSMutableDictionaryNSNumberNSStringintlongmainreturnunsignedvoid
The run, in numbers
- Lines
- 20
- Characters to type
- 624
- Tokens
- 135
- Three-star pace
- 60 tpm
At the three-star pace of 60 tokens a minute, this run takes about 135 seconds.
Step 3 of 3 in Collections, step 12 of 27 in Language basics.