OC4(数组)
1,不可变数组
1,数组是有序的,下标从0开始,只能存放对象类型的元素,与NSNumber、NSValue相联系
2,不可变数组的创建方法
NSArray *array1 = [[NSArray alloc]initWithObjects:@"zhonger",@"honghuang",@"taixu",@"zhili",nil];//nil不是对象,指示标记,告诉编译器,数组赋值结束
笑笑语法
NSArray *array3 = @[@"shuishen",@"huangshenme",@"youyisi",@"qiuxiang",@12];
3,数组的两个核心方法count、objectAtIndex
4,判断数组中是否包含某个元素
BOOL isTure =[array2 containsObject:@"zhuba"];
5,获取某个元素所在的数组下标
NSUInteger index = [array2 indexOfObject:@"bada"];
6,通过数组实现分割字符串和拼接字符串
NSString *str = @"zhonger m 19 f";
NSArray *resultArray =[str componentsSeparatedByString:@" "];
NSArray *array = @[@"bada",@"qiuxiang",@"zaiyiqi"];
NSString *resultStr = [array componentsJoinedByString:@"💗"];
2、可变数组
初始化方法
NSMutableArray *mArr = [[NSMutableArray alloc] initWithCapacity:0];
便利构造器
NSMutableArray *mArr1 = [NSMutableArray arrayWithCapacity:0];
字面量创建方式
NSMutableArray *mArr2 = [@[@"zhonger",@"dada",@"zhuzhu",@"linlin"] mutableCopy];
NSLog(@"mArr2 is %@",mArr2);
//往可变数组中添加元素 addObject:
[mArr addObject:@"123"];
NSLog(@"mArr is %@",mArr);
//往可变数组的制定位置,插入一个新元素
[mArr2 insertObject:@"qiuxiang" atIndex:2];
NSLog(@"mArr2 is %@",mArr2);
//移除可变数组中的某一个元素
[mArr2 removeObject:@"zhonger"];//删除指定元素
[mArr2 removeObjectAtIndex:3];//删除某个下标的元素
NSLog(@"mArr2 is %@",mArr2);
[mArr2 removeLastObject];//删除数组中的最后一个元素
NSLog(@"mArr2 is %@",mArr2);
[mArr2 removeAllObject];//删除数组中的所有元素
NSLog(@"mArr2 is %@",mArr2);
//替换可变数组中的某个元素
[mArr2 replaceObjectAtIndex:0 withObject:@"zhonger"];
[mArr2 replaceObjectAtIndex:1 withObject:@"taixu"];
NSLog(@"mArr2 is %@",mArr2);
//交换可变数组中两个元素的位置
[mArr2 exchangeObjectAtIndex:0 withObjectAtIndex:1];
NSLog(@"mArr2 is %@",mArr2);