1.创建不可变的空数组
NSArray *arr = [NSArray array];
NSLog(@"%ld", arr.count);
3.通过下标取值,返回一个对象
NSLog(@"%@",[arr objectAtIndex:1] );//方法1
NSLog(@"%@", arr[1]);//方法2
4.for循环对数组遍历
for (NSInteger i = 0; i < arr.count; i++) {
NSLog(@"%@", arr[i]);
}
5.判断6在不在数组里
NSLog(@"%d", [arr containsObject:@"6"]);
6.为Student类创建4个对象
Student *stu1 = [[Student alloc]initWithName:@"商帅"];
Student *stu2 = [[Student alloc]initWithName:@"腾飞"];
Student *stu3 = [[Student alloc]initWithName:@"刘珊珊"];
Student *stu4 = [[Student alloc]initWithName:@"杨林"];
//放到一个数组里(创建不可变数组并赋值)
NSArray *arr = [[NSArray alloc]initWithObjects:stu1,stu2,stu3,stu4 ,nil]; //方法1:自定义初始化
NSArray *arr = [NSArray arrayWithObjects:stu1, stu2, stu3, stu4,nil]; //便利构造器
NSArray *arr = @[stu1, stu2, stu3, stu4];//方法3:字面量
//遍历该数组
快速枚举:能快速遍历数组等容器对象 都是对容器里的每一元素的遍历
为了增加代码的阅读性,避免不必要的错误,尽量让forin的前面部分的类型和数组里元素类型相同
for (Student *stu in arr) {
NSLog(@"%@", stu.name);
}
7.数组的嵌套遍历
//将4个对象分别装在两个数组,然后再合并到一个数组,最后遍历学生姓名
NSArray *arr1 = @[stu1, stu2, stu3];
NSArray *arr2 = @[stu4];
NSArray *arr = @[arr1, arr2];
for (NSArray *temp in arr) {
for (Student *stu in temp) {
NSLog(@"%@", stu.name);
}
}
NSArray *arr2 = @[@"星期一", @"水电费", @"火车",@"哈哈"];
NSArray *arr = @[arr1, arr2];
//对arr进行遍历
for (NSArray *temp in arr) {
for (NSString *str in temp) {
NSLog(@"%@", str);
}
}
*****************************可变数组*****************************
1.创建可变空数组
NSMutableArray *arr = [[NSMutableArray alloc]init]; //自定义初始化
NSMutableArray *arr1 = [NSMutableArray array]; //便利构造器
2.不可变数组 变 可变数组
NSArray *arr = @[@"1", @"2"];
NSMutableArray *muArr = [NSMutableArray arrayWithArray:arr];
3.字符串操作
NSMutableArray *arr = [[NSMutableArray alloc]initWithObjects:@"1", @"2", @"3", @"4", nil];
(1)添加一个字符串
[arr addObject:@"234”]; //添加到数组的最后一位
NSLog(@"%@", arr);
(2)移除下标2的字符串
[arr removeObjectAtIndex:2];
NSLog(@"%@", arr);
(3)插入一个字符串
[arr insertObject:@"66" atIndex:1];
NSLog(@"%@", arr);
(4)替换一个字符串
[arr replaceObjectAtIndex:3 withObject:@"10"];
(5)交换两个字符串
[arr exchangeObjectAtIndex:2 withObjectAtIndex:3];
NSLog(@"%@", arr);
(6)清空数组
[arr removeAllObjects];
例题: for (Book *temp in bookArr) {
if ([temp.bookName isEqualToString:@"三国演义"]) {
temp.bookPrice = 200;
}
}