数组初始值的设置
NSArray *arr=@[@"1",@"2",@"3",@"4",@"5"];
数组里的元素个数
NSLog(@"%ld",arr.count);
取值
NSLog(@"%@",[arr objectAtIndex:1]);
NSLog(@"%@",arr[1]);
// 两种方法
对数组进行遍历
for (NSInteger i=0; i<arr.count; i++) {
NSLog(@"%@",arr[i]);
}
判断数组中是否包含 对象
NSLog(@"%d",[arr containsObject:@"3"]);
打印数组中的某个对象
NSLog(@"%@",student.name);
数组中添加对象
[student setNameStu:@"不好" age:19];
用点语法直接赋值
student.name = @"刘珊珊1111";
NSLog(@"%@", student.name);
用便利构造器的方法创建数组
NSArray *arr=[NSArray arrayWithObjects:student,student2,student3,student4, nil];
可变数组
// 空数组
NSMutableArray *arr1=[NSMutableArray array];
添加一个字符串
NSMutableArray *arr1=[[NSMutableArray alloc]initWithObjects:@"1",@"2",@"3",@"4",@"limuran", nil];
NSLog(@"%@",arr1);
// 添加到数组的最后一位
移除下标为2的字符串
[arr removeObjectAtIndex:2];
插入一个字符串
[arr insertObject:@"李牧燃" atIndex:3];
替换一个字符串
[arr replaceObjectAtIndex:2 withObject:@"腾飞"];
交换两个字符串
[arr exchangeObjectAtIndex:3 withObjectAtIndex:1];
清空数组
[arr removeAllObjects];
练习
/ 图书管理
// 1 使用可变数组管理所有书籍(定义Book类,包含书名和价格)
// 2 数组可以添加 删除书籍
// 3 可以从数组根据书名
// 定义三本书的字典
NSMutableDictionary *book1=[NSMutableDictionary dictionaryWithObjectsAndKeys:@"三国演义",@"name",@"100",@"price", nil];
NSMutableDictionary *book2=[NSMutableDictionary dictionaryWithObjectsAndKeys:@"水浒传",@"name",@"200",@"price", nil];
NSMutableDictionary *book3=[NSMutableDictionary dictionaryWithObjectsAndKeys:@"西游记",@"name",@"300",@"price", nil];
NSMutableArray *arr=[NSMutableArray arrayWithObjects:book1,book2,book3, nil];
// 2 数组可以添加 删除书籍
// 首先定义一个book类字典
NSMutableDictionary *book4=[NSMutableDictionary dictionaryWithObjectsAndKeys:@"HarryPotter",@"name",@"77",@"price", nil];
[arr addObject:book4];
[arr removeObject:book1];
for (NSMutableDictionary *dic in arr) {
for (NSString *str in dic) {
NSLog(@"%@",dic[str]);
}
}
[arr removeObject:book1];
// 可以从数组根据书名查找书籍,并修改书籍的价格
for (NSMutableDictionary *dic in arr) {
if ([dic[@"name"]isEqualTo:@"水浒传"]) {
[dic setObject:@"200" forKey:@"price"];
}
}
//