今天讲Objective-C的可变数组,之前讲的NSArray是不可变的,immutable,今天讲NSMutableArray,它是可变的。
Mutability
Although the NSArray class itself is immutable, this has no bearing on any collected objects. If you add a mutable string to an immutable array, for example, like this:
NSMutableString *mutableString = [NSMutableString stringWithString:@"Hello"];
NSArray *immutableArray = @[mutableString];
there’s nothing to stop you from mutating the string:
if ([immutableArray count] > 0) {
id string = immutableArray[0];
if ([string isKindOfClass:[NSMutableString class]]) {
[string appendString:@" World!"];
}
}
If you need to be able to add or remove objects from an array after initial creation, you’ll need to use NSMutableArray, which adds a variety of methods to add , remove or replace one or more objects:
NSMutableArray *mutableArray = [NSMutableArray array];
[mutableArray addObject:@"gamma"];
[mutableArray addObject:@"alpha"];
[mutableArray addObject:@"beta"];
[mutableArray replaceObjectAtIndex:0 withObject:@"epsilon"];
This example creates an array that ends up with the objects @"epsilon", @"alpha", @"beta".
It’s also possible to sort a mutable array in place, without creating a secondary array:
[mutableArray sortUsingSelector:@selector(caseInsensitiveCompare:)];
In this case the contained items will be sorted into the ascending, case insensitive order of @"alpha", @"beta", @"epsilon".