可变数组的操作插入删除

1.添加对象到数组中
NSMutableArray *arr = [NSMutableArray arrayWithObjects:
@”one”, @”two”, @”three”, @”four”, @”five”, @”six”, nil];
NSMutableArray *arr = [NS]
[arr addObject:@”five”];
2.在指定位置添加对象
[arr insertObject:@”ten” atIndex:3];
3.删除最后一个对象
[arr removeLastObject];
4.替换指定位置
[arr replaceObjectAtIndex:3 withObject:@”FIVE”];
5.创建内存
NSMutableArray *arr1 = [NSMutableArray arrayWithCapacity:20];
6.将一个数组添加到另外一个数组中
[arr addObjectsFromArray:@[@”seven”, @”eight”]];
7.交换数组元素的位置
[arr exchangeObjcetAtIndex: 3 withObjectAtIndex: 5];
8.删除指定范围的对象
[arr removeObject:@”three”];
[arr removeObject:@”FIVE” inRange:NSMakeRange(1,5)];
9.删除数组中的指定元素
[arr removeObjectsInArray:
@[@”one”, @”two”]];
10.用一个数组指定范围的元素代替另外一个数组中的元素
[arr replaceObjectsInRange:NSMakeRange(0,3)
withObjectsFromArray:@[@”one”, @”two”, @”three”]];
11.修改数组
[arr setArray:@[@”Four”, @”Five”, @”Six”]];
12.在指定位置添加连续的数组元素
[arr insertObjects:@[@”dog”,@”cat”, @”elephant”]] atIndexes:
[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(2, 3)];
注:NSMakeRange(2,3)是指从数组下标为2的位置开始,向后连续添加3个元素(添加元素的个数必须与insertObjects后的元素个数相对应)
13.删除指定范围的元素
[arr removeObjectsAtIndexes:
[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(1, 2)]];
14.在指定位置添加指定元素
NSMutableIndexSet *indexset = [NSMutableIndexSet indexSet];
[indexset addIndex:1];
[indexset addIndex:3];
[indexset addIndex:4];
[arr replaceObjectsAtIndexes:indexset
withObjects:@[@”hello”, @”jian”, @”shu”]];
//一.数组不能int ,char,double等基本数据类型不能直接保存,需要通过转换成对象才能加入数组。
/*
1、NSArray 不可变数组
[array count](array.count) : 数组的长度。
[array objectAtIndex 0]: 传入数组脚标的id 得到数据对象。
[arrayWithObjects; …] :向数组对象初始化赋值。这里可以写任意对象的指针,结尾必须使用nil。
*/

NSArray *array = [[NSArray alloc] initWithObjects:@"a",@"haha",@"傻逼",@"二货", nil];
NSLog(@"打印结果:%@",[array objectAtIndex:2]);
//打印结果:打印结果:傻逼

//二.可变数组的操作

//1.在数组中插入一个元素
NSMutableArray *muArray = [[NSMutableArray alloc] init];
NSObject *obj = [[NSObject alloc] init];
[muArray addObject:@"对象1a"];
[muArray addObject:@"对象2b"];
[muArray addObject:@"对象3c"];
[muArray addObject:@"对象4d"];
[muArray addObject:@"对象1a"];
[muArray addObject:obj];

[muArray insertObject:@"kiven Dourntarnt" atIndex:1];
NSLog(@"muArray = %@",muArray);


//2.删除数组中元素
NSString *str1 = @"傻逼一号";
NSString *str2 = @"傻逼二号";
NSString *str3 = @"傻逼一号";
NSString *str4 = @"傻逼三号";

NSMutableArray *muArray2 = [[NSMutableArray alloc] init];
[muArray2 addObject:str1];
[muArray2 addObject:str2];
[muArray2 addObject:str3];
[muArray2 addObject:str4];

// [muArray2 removeObject:str1];
// [muArray2 removeObjectIdenticalTo:str3];

//3.替换数组某一个位置的元素

[muArray2 replaceObjectAtIndex:1 withObject:@"牛逼一号"];



//4.删除一定范围内的数组元素
[muArray2 removeObjectIdenticalTo:str1 inRange:NSMakeRange(0, 2)];

for (NSString *string in muArray2) {
    NSLog(@"jieguo = %@",string);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值