数组里面存放的必须是对象 只要是对象都可以放在数组里面 类型可以不一致,但是必须是对象
1.数组创建对象的方式
1.1 初始化方法
NSArray *array =[[NSArray alloc] initWithObjects:@"xiaowan",@"xiaoyun",@"xiaohong", nil];
//nil代表数组的结束
NSLog(@"array = %@",array); // array = (xiaowan,xiaoyun, xiaohong)
1.2遍历构造器
NSArray *array1 = [NSArray arrayWithObjects:@"xiaowan",@"xiaoyun",@"xiaohong",nil];
NSLog(@"array1 = %@",array1);// array1 = (xiaowan,xiaoyun, xiaohong)
1.3 字面量
NSArray *array2 =@[@"xiaowan",@"xiaoyun",@"xiaohong"];
NSLog(@"array2 = %@",array2); // array2 =@"xiaowan",@"xiaoyun",@"xiaohong"
2.计算数组元素的个数
NSArray *array3 =[[NSArray alloc]initWithObjects:@"xiaowan",@"xiaoyun",@"xiaohong", nil];
NSUInteger a = array3.count;//count只有get方法
NSLog(@"a = %lu",a);//a = 3
//3.如何获取数组的元素
NSArray *array4 = [NSArray arrayWithObjects:@"xiaowan",@"xiaoyun",@"xiaohong",@"xiaofang",@"xiaohua",nil];
//3.1调用方法去获取
NSString *str = [array4 objectAtIndex:4];
NSLog(@"str = %@",str); //str = xiaohua
//3.2.字面量
NSArray *str1 = array4[1];
NSLog(@"str1 = %@",str1); //str1 = xiaoyun
//3.3获取第一个
NSString *str2 = [array4 firstObject];
NSLog(@"str2 = %@",str2); //str2 = xiaowan
//3.4获取最后一个
NSString *str3 = [array4 lastObject];
NSLog(@"str3 = %@",str3); //str3 = xiaohua
小结:当数组元素为空时,调用objectAtIndex和字面量取固定元素的时候会崩溃,但是用firstObject和lastObject时,不会崩溃,打印出来是null
//4.根据元素获取元素对应的索引以及判断数组中是否包含某个指定的对象
NSArray *array5 = [NSArray arrayWithObjects:@"a",@"b",@"c",@"d",@"e",nil];
NSUInteger i= [array5 indexOfObject:@"bb"];
//如果有 则返回对应的下标 如果没有 则返回无穷大的数
NSLog(@"i = %lu",i);// i = 9223372036854775807
//判断数组里是否包含某一个特定的元素
BOOL isBool =[array5 containsObject:@"a"];
NSLog(@"%d",isBool);//1 bool类型 如果有 就返回1 没有就返回0
//判断两个数组是否相等
NSArray *array6 = [NSArray arrayWithObjects:@"aa",@"bb",@"cc",nil];
BOOL is = [array5 isEqualToArray:array6];
NSLog(@"is = %d",is); //is = 0 不相等
//5.NSarray 和字符串的转化
//按照给定的字符串进行截取 将截取的多段字符串放到数组里
NSString *st = @"http://www.imanhua.com/Cover/2011-10/hyrz.jpg &http://www.imanhua.com/Cover/2011-09/op.jpg&http://www.imanhua.com/Cover/2012-04/yjdwb.jpg";
NSArray *arr =[st componentsSeparatedByString:@"&"]; //按 & 分离字符串
NSLog(@"arr = %@",arr);
arr = ("http://www.imanhua.com/Cover/2011-10/hyrz.jpg",
"http://www.imanhua.com/Cover/2011-09/op.jpg",
"http://www.imanhua.com/Cover/2012-04/yjdwb.jpg" )
//字符串拼接
NSString *strs = [arr componentsJoinedByString:@"**"]; //按**进行字符串拼接
NSLog(@"strs = %@",strs);
// strs = http://www.imanhua.com/Cover/2011-10/hyrz.jpg**http://www.imanhua.com/Cover/2011-09/op.jpg**http://www.imanhua.com/Cover/2012-04/yjdwb.jpg