//NSMutableArray 增删改查
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) { @autoreleasepool { #pragma mark - NSMutabelArray //可变数组 NSMutableArray
#pragma mark 创建数组
//空数组 NSMutableArray *array = [NSMutableArray array];
//创建时初始化一个元素 NSMutableArray *array2 = [NSMutableArray arrayWithObject:@"one"];
//创建时初始化多个元素 NSMutableArray *array3 = [NSMutableArray arrayWithObjects:@"one",@1,@2,@"three", nil];
//创建时指定长度 NSMutableArray *array4 = [NSMutableArray arrayWithCapacity:5];
NSLog(@"array = %@,%p",array,&array); NSLog(@"array2 = %@",array2); NSLog(@"array3 = %@",array3); NSLog(@"array4 = %@",array4);
#pragma mark 添加数组元素
//添加元素一个元素 [array addObject:@"ten"]; NSLog(@"array = %@,%p",array,&array);
//添加元素到指定位置 [array insertObject:@"money" atIndex:0]; NSLog(@"%@",array);
#pragma mark 删除元素
//根据对象内容元素 [array removeObject:@"ten"]; NSLog(@"%@",array);
//根据位置删除元素 [array removeObjectAtIndex:0]; NSLog(@"%@",array);
//全部删除 [array3 removeAllObjects]; NSLog(@"%@",array3);
#pragma mark 修改元素 //修改元素 [array2 replaceObjectAtIndex:0 withObject:@"four"]; NSLog(@"array2 = %@",array2);
//简化修改方法 array2[0] = @"five"; NSLog(@"%@",array2);
#pragma mark 查找元素
//查找元素 //返回BOOL类型 BOOL arr = [array2 containsObject:@"five"]; NSLog(@"%d",arr);
#pragma mark 交换元素 NSMutableArray *array5 = [NSMutableArray arrayWithObjects:@1,@2,@3,@4,@5, nil];
//!交换数组元素(常用) [array5 exchangeObjectAtIndex:0 withObjectAtIndex:4]; NSLog(@"%@",array5);
#pragma mark - 错误用法
NSMutableArray *array6 = @[@"one",@"two",@"three"]; // [array6 addObject:@"five"]; //使用@[@“”]是给NSArray 不可变数组赋值,所以不能修改 NSLog(@"%@",array6); } return 0; }
|