一.可变数组创建和不可变数组类似
二.可变数组操作
首先我们创建一个空的可变数组
NSMutableArray *mArr = [[NSMutableArray alloc]init];
1.添加元素
[mArr addObject:@"one"]; [mArr addObject:@"two"]; [mArr addObject:@"three"]; NSLog(@"mArr is %@",mArr);
输出结果:
2016-06-27 16:06:54.676 OcTest[964:728178] mArr is ( one, two, three ) Program ended with exit code: 0
2.删除元素
[mArr removeObject:@"one"]; [mArr removeAllObjects];
3.置换元素
[mArr exchangeObjectAtIndex:0 withObjectAtIndex:2];
三.应用实例:将字符串拆分成数组反向输出
NSString *str = @"this is an Object-C program"; NSArray *arr = [str componentsSeparatedByString:@" "]; NSMutableArray *mArr = [[NSMutableArray alloc]init]; NSEnumerator *enu = [arr reverseObjectEnumerator]; id obj; while(obj = [enu nextObject]){ [mArr addObject:obj]; } NSLog(@"mArr is %@",mArr);
输出结果:
2016-06-27 16:16:45.198 OcTest[992:754324] mArr is ( program, "Object-C", an, is, this ) Program ended with exit code: 0
未来的你会感谢今天努力的自己
------Alen