NSMutableArray是可变数组,是NSArray的子类。
Foundation类为使用数组提供了许多便利,然而,如果使用复杂的运算法则操纵大型数字数组,学习使用C语言提供的低级数组构造执行这种任务可能更加有效,对于内存使用和执行速度来说,都是如此。
| 常用的NSMutableArray方法 | |
| 方法 | 描述 |
| +(instancetype) array | 创建一个空数组 |
| +(instancetype) arrayWithCapacity: size | 使用指定的初始size创建一个数组 |
| -(instancetype) initWithCapacity: size | 使用指定的初始size初始化新分配的数组 |
| -(void) addObject: obj | 将对象obj添加到数组的末尾 |
| -(void) insertObject: obj atIndex: i | 将对象obj插入到数组的i元素 |
| -(void) replaceObjectAtIndex: i withObject: obj | 将数组中序号为i的对象用对象obj替换 |
| -(void) removeObject: obj | 从数组中删除所有的obj |
| -(void) removeObjectAtIndex: i | 从数组中删除元素i,将序号为i+1的对象移至数组的结尾 |
| -(void) sortUsingSelector: (SEL) selector | 用selector指定的比较方法将数组排序 |
| -(void) sortUsingComparator: (NSComparator) block | 通过执行区块block对数组进行排序 |
说明:
obj、obj1、和obj2是任意对象,i是呈现数组中有效索引号的NSUInteger整数,selector是SEL类型的selector对象,size是一个NSUInteger整数。
示例一:
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
// 创建一个空的可变数组对象
NSMutableArray *numbers = [NSMutableArray array];
int i;
// 创建0-4数字的数组
for (i = 0; i < 5; ++i) {
// 数组元素只能是数字对象(NSNumber)
numbers[i] = @(i);
// 也可以这样写
//[numbers addObject: @(i)];
}
// 遍历数组与显示其值
for (i = 0; i < 5; ++i) {
NSLog(@"%@", numbers[i]);
}
// 使用带有%@格式的NSLog显示
NSLog(@"====== Using a single NSLog");
NSLog(@"%@", numbers);
}
return 0;
}