OC 数组特点: 可以存储不同类型的对象,oc的数组 只能存储对象
数组可以遍历,占用的内存空间是连续的. oc中的数组不是把整个对象存在数组中 ,而是把指针存到内存中.
-----------------------------------------------------------------------------------------------------------------
NSArray *nsArray = [[NSArray alloc] initWithObjects:@"1",@"2",@"3",@"4",@"5", nil];
//数组长度
NSInteger count = [nsArray count];
NSLog(@"count = %ld",(long)count);
//判断数组中是否包含对应对象
BOOLisHave = [nsArray containsObject:@"3"];
if(isHave)
NSLog(@"包含");
else
NSLog(@"不包含");
//取出数组中首个元素
NSString*firstStr = [nsArray firstObject];
NSLog(@"firstStr =%@",firstStr);
//取出数组中最后一个元素
NSString*lastStr = [nsArray lastObject];
NSLog(@"lastStr = %@",lastStr);
//取出数组中下标为3的元素
NSString*threeStr = [nsArray objectAtIndex:3];
NSLog(@"threeStr = %@",threeStr);
//打印对应元素的下标
NSInteger index = [nsArray indexOfObject:@"2"];
NSLog(@"index =%ld",(long)index);
-----------------------------------------------------------------------------------------------------------------
//数组遍历(1.基本的for循环,通过下标逐一取出查看.for in快速枚举.3.枚举器(迭代器))
Person *p = [[Person alloc] init];
p.personName=@"公孙离";
NSArray*personArray = [[NSArray alloc]initWithObjects:@"a",@"b",p,@"c",nil];
// c语言版本:c89,c95,c99
// c 89 int i 需要生命到外面
for(inti =0;i
NSString*arrayStr = [nsArray objectAtIndex:i];
NSLog(@"arrayStr =%@",arrayStr);
}
for(inti =0;i
id personStr = [personArray objectAtIndex:i];
if([personStr isKindOfClass:[Person class]]){
Person*person = (Person*)personStr;
NSLog(@"personName2 =%@",person.personName);
}else{
NSString*personArray2 = (NSString*)personStr;
NSLog(@"personArray2=%@",personArray2);
}
}
-----------------------------------------------------------------------------------------------------------------
//快速枚举
//迭代相同类型元素的数组
for(NSString*personStr2innsArray) {
NSLog(@"personStr2 =%@",personStr2);
}
//迭代不同类型元素的数组
for(id personStr3 in personArray) {
if([personStr3 isKindOfClass:[Person class]]) {
Person*person = (Person*)personStr3;
NSLog(@"personName3 =%@",person.personName);
}else{
NSString*personArray3 = (NSString*)personStr3;
NSLog(@"personArray3 =%@",personArray3);
}
}