NSMutableArray (可变数组)继承NSArry(不可变数组)
1.创建对象的方式
1.1初始化方式
NSMutableArray *array = [[NSMutableArray alloc]initWithCapacity:10];
1.2遍历构造器
NSMutableArray *array1 =[NSMutableArray arrayWithCapacity:10];
1.3字面量
NSMutableArray *array2 =[@[@"aa",@"bb"]mutableCopy];
2.添加元素
2.1直接添加元素
[array addObject:@"zhangsan"];
NSLog(@"array = %@",array);// array = zhangsan
[array addObject:@"wangwu"];
NSLog(@"array = %@",array);
/*array = (
zhangsan,
wangwu
)
*/
2.2指定位置交通添加
//在下标是1的地方添加zhaoliu
[array insertObject:@"zhaoliu" atIndex:1];
NSLog(@"array = %@",array);
/*数组是从0开始算起
array = (
zhangsan,
zhaoliu,
wangwu
)
*/
//在下标是3的地方添加zhangsan
[array insertObject:@"zhangsan" atIndex:3];
NSLog(@"array = %@",array);
/*(
zhangsan,
zhaoliu,
wangwu,
zhangsan
)*/
3.删除
3.1移除所有zhangsan的元素
[array removeObject:@"zhangsan"];
NSLog(@"array = %@",array);
/*(
zhaoliu,
wangwu
)*/
3.2移除下标是1的元素
[array removeObjectAtIndex:1];
NSLog(@"array = %@",array);
/*(
zhaoliu
)*/
3.3移除最后一个元素
[array removeLastObject];
3.4//移除所有元素(删除后数组为空)
[array removeAllObjects];
给数组添加元素
[array addObject:@"zhangsan"];
[array addObject:@"lisi"];
[array addObject:@"wangwu"];
[array addObject:@"zhangsan"];
NSLog(@"array = %@",array);
/*array = (
zhangsan,
lisi,
wangwu,
zhangsan
)*/
3.4移除某一个范围
[array removeObjectsInRange:NSMakeRange(1,3)];
NSLog(@"array = %@",array);
/*array = (
zhangsan
)*/
//移除某一个范围后面的元素
//[array removeObject:@"zhangsan"inRange:NSMakeRange(1, 3)];
给数组添加元素
[array addObject:@"lisi"];
[array addObject:@"wangwu"];
[array addObject:@"zhaoliu"];
NSLog(@"array = %@",array);
/*array = (
zhangsan,
lisi,
wangwu,
zhaoliu
)*/
4.交换指定位置上的两个元素
[array exchangeObjectAtIndex:0 withObjectAtIndex:2];
NSLog(@"array1 = %@",array);
/* (
wangwu,
lisi,
zhangsan,
zhaoliu
)*/
5.替换数组中的一个元素
[array replaceObjectAtIndex:3 withObject:@"xueren"];
NSLog(@"array2 = %@",array);
/* (
wangwu,
lisi,
zhangsan,
xueren
)*/
For循环里面不允许去更改数组的长度,但是移除最后一个元素不影响数组的运行
//如果删除lisi 数组的长度就会改变从而崩溃
for (NSString *str in array) {
if ([str isEqualToString:@"xueren"]) {
[array removeObject:@"xueren"];
}
}
NSLog(@"%@",array);
/*(
lisi,
zhaoliu
)*/