不可变数组的初始化
数组对象的实例化
数组里存的都是对象
任意对象都可以存进数组
NSArray *arr1 = [[NSArray alloc]initWithObjects:@"1",@"hello",@"world",@"JayZhou", nil];
NSArray *arr2 = [[NSArray alloc]initWithArray:arr1];
NSArray *arr3 = [NSArray arrayWithObjects:@"a",@"b",@"c",nil];
NSArray *arr4 = [NSArray arrayWithArray:arr3];
Person *per = [[Person alloc]init];
Dog *d = [[Dog alloc]init];
NSString *str = @"hello world";
NSArray *arr5 = [[NSArray alloc]init];
NSArray *array = @[per,d,str,arr5];
NSLog(@"array= %@",array);
NSArray *s = [[NSArray alloc]initWithObjects:@"s",@"b",@"m", nil]; NSArray *s1 = [[NSArray alloc]initWithArray:s];
NSLog(@"s= %@ s1= %@",s,s1);
不可变数组的常用操作 (偷个懒下面的就不贴打印结果了 )
NSString *string = [s objectAtIndex:1];//获取指定下标的元素
//获取元素的简写 存的是什么类型的对象,获取元素 就定义相对应的类型来接
NSString *str = arr[1];//[ ]里是下标
NSUInteger index = [s indexOfObject:@"1"];
if (index == NSNotFound) {
NSLog(@"不在数组中");//这里使用指针进行比较,如果存在,返回指定的下标,如果不存在,则返回NSNotFund
}
NSUInteger index1 = [s indexOfObject:@"b" inRange:NSMakeRange(0, 1)];
if (index1 == NSNotFound) {
NSLog(@"不在数组中");
}
//获取第一个元素
NSString *str3 = [arr firstObject];
NSLog(@"str3= %@",str3);
//如何获取最后一个元素
NSString *str2 = [arr lastObject];
NSLog(@"str2= %@",str2);
BOOL ret = [arr containsObject:@"f"];
if (ret) {
NSLog(@"包含这个元素");
}else{
NSLog(@"不包含");
}
//起始下标指的就是第几个元素,长度就是代表获取多少个元素
NSRange range = {0,2};//长度为2就只是获取2个元素,起始下标为0
NSArray *arr1 = [arr subarrayWithRange:range];
小练习
创建一个数组,NSArray *arr = @[@“1”,@“2”,@“3”,@“4”,@“5”,@“6”,@“7”,@“8”,@“9”,@“10”];
找出该数组中下标能整除2的元素,并且输出;
NSArray *arr1 = [NSArray arrayWithObjects:@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9", @"10",nil];
for (NSInteger i = 0; i<[arr1 count]; i++) {
if ( i%2==0) {
NSLog(@"str= %@",arr1[i]);
}
}