您的位置:首页 > 移动开发 > IOS开发

iOS 中的可遍数组NSMutableArray

2016-05-06 14:16 337 查看
创建NSMutableArray可变数组
1     //对象方法创建可变数组
2     NSMutableArray *array1 = [[NSMutableArray alloc] init];
3     //类方法创建可变数组
4     NSMutableArray *array2 = [NSMutableArray arrayWithCapacity:0];


向数组中添加元素
1     NSMutableArray *array = [[NSMutableArray alloc] init];
2     NSArray *tmp = [NSArray arrayWithObjects:@"jing", @"dian", @"ying", @"xue", @"yuan", nil];
3     [array addObject:@"bei"];
4     [array addObjectsFromArray:tmp];
5     //- (void)insertObject:(id)anObject atIndex:(NSUInteger)index;
6     //作用:数组中任意一个位置插入元素
7     [array insertObject:@"hao" atIndex:1];
8     NSLog(@"%@", array);


在数组中删除元素
NSMutableArray *array = [NSMutableArray arrayWithObjects:@"nan", @"jing", @"hao", nil];
#if 0
//- (void)removeObjectAtIndex:(NSUInteger)index;
//作用:删除数组中指定下标的元素
[array removeObjectAtIndex:2];
#endif
#if 0
//- (void)removeObject:(id)anObject;
//作用:删除数组中指定的元素(有多少删多少)
[array removeObject:@"hao"];
#endif
#if 0
//- (void)removeObjectsInRange:(NSRange)range;
//作用:从某位置起,删除某长度的元素
[array removeObjectsInRange:{1, 2}];
#endif
//- (void)removeAllObjects;
//作用:删除数字中的全部元素
[array removeAllObjects];
NSLog(@"%@", array);


替换数组中某个位置的元素
1     NSMutableArray *array = [NSMutableArray arrayWithObjects:@"nan", @"jing", @"hao", nil];
2     //- (void)replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
3     //作用:替换数组中指定下标的元素
4     [array replaceObjectAtIndex:0 withObject:@"bei"];


交换数组中某两个指定位置的元素
NSMutableArray *array = [NSMutableArray arrayWithObjects:@"nan", @"jing", @"hao", nil];
//- (void)exchangeObjectAtIndex:(NSUInteger)idx1 withObjectAtIndex:(NSUInteger)idx2;
//作用:交换数组中指定下标的两个元素
[array exchangeObjectAtIndex:0 withObjectAtIndex:2];
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: