创建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];