一. 创建不可变字典的方式:
//字典的字面量,前key后value
NSDictionary *dic =@{@"1":@"2",@"3":@"4"};
NSDictionary *dic = [[NSDictionaryalloc]init];
NSDictionary *dic = [NSDictionary dictionary];
NSDictionary *dic = [[NSDictionary alloc]initWithObjectsAndKeys:@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",nil];
NSLog(@"%@",dic);
// Key 是唯一的,但是Value是可以重复的
// key 不能为空.
二. 不可变字典的属性与方法:
//1.属性:有多少键值对 -- count:
NSLog(@"%ld",dic.count);
// 2. objectForKey --
根据Key找value:
NSLog(@"%@",[dic objectForKey:@"2"]);
NSLog(@"%@",dic[@"2"]);
//3. 获取所有的key和value --
NSLog(@"%@",dic.allKeys);
NSLog(@"%@",dic.allValues);
三. 创建可变字典的方式:
NSMutableDictionary *dic = [NSMutableDictionarydictionaryWithObjectsAndKeys:@"1",@"2",@"3",@"4",@"5",@"6",nil];
//
遍历字典.
打出所有Vaule
for (NSInteger i =
0; i < dic.allKeys.count; i++) {
NSLog(@"%@",dic.allValues[i]);
}
for (NSString *str
in dic) {
NSLog(@"%@",str);//
打出字典的Key.
NSLog(@"%@",dic[str]);//打出Vaule.
}
四.可变字典的属性与方法:
NSMutableDictionary *dic1 = [[NSMutableDictionaryalloc]initWithObjectsAndKeys:@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",nil];
//1.可变键值对添加(当key不存在时就进行添加,当key存在时,就进行vaule值的修改.)
-- setObject forKey:
[dic1setObject:@"10"forKey:@"11"];
NSLog(@"%@\n",dic1);
[dic1setObject:@"1000"forKey:@"11"];
NSLog(@"%@",dic1);
//2. 移除键值对
[dic1 removeObjectForKey:@"8"];
NSLog(@"%@",dic1);
//3. 全部移除
[dic1 removeAllObjects];
NSLog(@"%@",dic1);
//4. setObject
是字典自己方法,setVaule是KVC的方法,即使效果一样,但以后对字典进行操作还用setObject.
[dic1setValue:@"100"forKey:@"10"];
五.字典与数组的嵌套:
//1. 字典里对象是数组.
NSArray *arr1 =
@[@"1",@"2",@"3",@"4"];
NSArray *arr2 =
@[@"5",@"6",@"7",@"8"];
NSMutableDictionary *dic = [NSMutableDictionarydictionaryWithObjectsAndKeys:arr1,@"arr1",arr2,@"arr2",nil];
//
遍历.
for (NSString *keyin dic) {
//
针对对应的key 找到vaule,vaule是一个数组,所以用一个数组对象来接受.
NSLog(@"%@",key);
NSArray *arr = dic[key];
for (NSString *vaulein arr) {
NSLog(@"%@",vaule);
}
}
//2. 数组里对象是字典.
NSDictionary *dic1 = [NSDictionarydictionaryWithObjectsAndKeys:@"杨林",@"name",@"19",@"age",nil];
NSDictionary *dic2 = [NSDictionarydictionaryWithObjectsAndKeys:@"刘鑫狗",@"name",@"20",@"age",nil];
NSDictionary *dic3 = [NSDictionarydictionaryWithObjectsAndKeys:@"刘伊茹",@"name",@"0",@"age",nil];
NSArray *arr =
@[dic1,dic2,dic3];
for (NSDictionary *dicin arr) {
for (NSString *keyin dic) {
NSLog(@"%@",dic[key]);
}
}
六.三层嵌套的练习:
NSDictionary *dic1 = [NSDictionarydictionaryWithObjectsAndKeys:@"杨林",@"name",@"19",@"age",nil];
NSDictionary *dic2 = [NSDictionarydictionaryWithObjectsAndKeys:@"刘鑫狗",@"name",@"20",@"age",nil];
NSDictionary *dic3 = [NSDictionarydictionaryWithObjectsAndKeys:@"刘伊茹",@"name",@"0",@"age",nil];
NSArray *arr1 =
@[dic1,dic2];
NSArray *arr2 =
@[dic3];
NSDictionary *Bdic = [NSDictionarydictionaryWithObjectsAndKeys:arr1,@"arr1",arr2,@"arr2",nil];
for (NSString *keyBin Bdic) {
NSArray *arr =Bdic[keyB];
for (NSDictionary *sdicin arr) {
for (NSString *keyin sdic) {
NSLog(@"%@",sdic[key]);
}
}
}
版权声明:本文为博主原创文章,未经博主允许不得转载。