//创建字典对象
NSDictionary *dic=[[NSDictionary alloc]init];
NSDictionary *dic=[[NSDictionary alloc]initWithObjectsAndKeys:@"1",@"2",@"3",@"4",@"5",@"6", nil];
NSLog(@"%@",dic);
//key是唯一的,但是value可以重复
//key不能为空
NSLog(@"%ld",dic.count);//当前有多少键值对
NSLog(@"%@",[dic objectForKey:@"2"]);//通过key找到对应的value
NSLog(@"%@",dic[@"2"]);//dic[对应的key] (语法糖)
//获取字典里所有key和所有value
NSLog(@"%@",dic.allKeys);
NSLog(@"%@",dic.allValues);
//可变的字典
NSMutableDictionary *dic1=[NSMutableDictionary dictionaryWithObjectsAndKeys:@"1",@"2",@"3",@"4",@"5",@"6", nil];
//for遍历字典dic1for(NSInteger i=0;i<dic1.allkeys.count;i++){
NSLog(@"%@",dic1.allValues[i]);
}
//forin前部分是字典里的key
for(NSString *str in dic1){
NSLog(@"%@",str);//找key
NSLog(@"%@",dic1[str]);//找value
//对可变的字典,当前key不存在的时候,是进行键值对的添加,当key存在的时候,进行值的修改
//移除键值对
[dic removeObjectForKey:@"8"];
NSLog(@"%@",dic);
[dic removeAllObjects];
NSLog(@"%@",dic);
//setObject是字典自己的方法,setValue是KVC的方法,即使效果一样,但以后要对字典进行操作,还是用setObject
[dic setValue:@"50" forKey:@"80"];
NSLog(@"%@",dic);
//定义两个书的字典 图书管理
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 *bookArr=[NSMutableArray arrayWithObjects:book1,book2,book3, nil];
//1.使用可变数组管理所有书籍{定义book类,包含书名和价格}
//2.数组可以添加删除书籍
NSMutableDictionary *booknew=[NSMutableDictionary dictionaryWithObjectsAndKeys:@"暮光之城",@"name",@"400",@"price", nil];
[bookArr addObject:booknew];
for (NSMutableDictionary *dic in bookArr) {
NSLog(@"%@",dic[@"name"]);
}
NSLog(@"\n");
for (NSInteger i=0; i<bookArr.count; i++) {
if ([bookArr[i][@"name"] isEqualToString:@"西游记"]) {
[bookArr removeObject:bookArr[i]];
i--;
}
}
for (NSMutableDictionary *dic in bookArr) {
NSLog(@"%@",dic[@"name"]);
}
NSLog(@"\n");
//3.可以从数组根据书名查找书籍,并修改书籍的价格
for (NSMutableDictionary *dic in bookArr) {
if ([dic[@"name"]isEqualToString:@"水浒传"]) {
[dic setObject:@"1000" forKey:@"price"];
}
}
for (NSMutableDictionary *dic in bookArr) {
NSLog(@"%@",dic[@"price"]);
}
NSLog(@"\n");
//4.展示所有书籍清单
for (NSMutableDictionary *dic in bookArr) {
NSLog(@"%@",dic[@"name"]);
}