[oc学习日记]字典
1 //字典的创建 2 NSDictionary *d1 = [NSDictionary dictionary]; 3 //将创建的字典的内容设置为制定的文件的内容 4 NSString *path = @"";//文件路径 5 NSDictionary *d2 = [NSDictionary dictionaryWithContentsOfFile:path]; 6 //创建具有一个键值的字典 7 NSDictionary *d3 = [NSDictionary dictionaryWithObject:@"s" forKey:@"s"]; 8 //创建具有多个键值的字典 键值对必需对应 9 //值在前 键在后 10 NSDictionary *d4 = [NSDictionary dictionaryWithObjectsAndKeys:@"ss",@"2", 11 @"ss",@"1", 12 nil]; 13 14 //利用数组创建字典 15 NSArray *key = @[@"2",@"3",@"4"]; 16 NSArray *obj = @[@"ss",@"ff",@"gg"]; 17 NSDictionary *d5 = [NSDictionary dictionaryWithObjects:obj forKeys:key]; 18 //便捷方式 19 //键在前 值在后 20 NSDictionary *d6 = @{ 21 @"2":@"d", 22 @"3":@"d"}; 23 24 //init初始化 25 //将初始化的字典内容设置为指定文件内容 26 NSDictionary *dd = [[NSDictionary alloc]initWithContentsOfFile:path]; 27 //初始化具有多个键-值的字典(利用数组) 28 NSDictionary *dd1 = [[NSDictionary alloc]initWithObjects:obj forKeys:key]; 29 //初始化具有多个键-值的字典 30 NSDictionary *dd2 = [[NSDictionary alloc]initWithObjectsAndKeys: 31 @"ss",@"2", 32 @"ss",@"1", nil]; 33 34 35 36 //字典基本操作 37 //字典是无序的 键不可以重复 值可以重复 38 //返回所有键 39 NSLog(@"%@",[dd2 allKeys]); 40 //返回所有值 41 NSLog(@"%@",[dd2 allValues]); 42 //返回所有值对应的键 43 NSLog(@"%@",[dd2 allKeysForObject:@"ss"]); 44 //返回对应键的值 最常见 最重要 45 NSLog(@"%@",[dd2 objectForKey:@"ss"]); 46 //键值对 47 NSLog(@"%zi",dd2.count); 48 49 50 //不可变字典 51 //创建 52 NSMutableDictionary *dic = [NSMutableDictionary dictionary]; 53 //分配空间 54 NSMutableDictionary *dic1 = [[NSMutableDictionary alloc]initWithCapacity:10]; 55 //创建并赋值 56 NSMutableDictionary *dic2 = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"ss",@"2", 57 @"ss",@"1", nil]; 58 //添加键值对 59 [dic2 setObject:@"s" forKey:@"sdads"]; 60 //删除所有键值对 61 [dic2 removeAllObjects]; 62 //删除指定键对应的键值对 63 [dic2 removeObjectForKey:@"sd"]; 64 65 66 //字典的遍历 67 //快速遍历 68 for (id key in dic2) { 69 NSLog(@"%@ = %@",key,[dic2 objectForKey:key]); 70 } 71 //代码块遍历 72 [dic2 enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { 73 NSLog(@"%@ %@",key,obj); 74 }]; 75 //迭代器遍历 76 //可以输出键和值 77 NSEnumerator *en = [dic2 keyEnumerator];//将所有键装入数组 78 id key2 = nil; 79 while (key2 = [en nextObject]) { 80 NSLog(@"%@ %@",key2,[dic2 objectForKey:key2]); 81 } 82 NSEnumerator *en1 = [dic2 objectEnumerator];//将所有值装入数组 83 //只可以输出值 84 id obj3 = nil; 85 while (obj3 = [en1 nextObject]) { 86 NSLog(@"%@", obj); 87 } 88 89 90 //键给空值会异常 值给控制就是结束标志
补充一点:
如果将自定义的类对象封装进字典
可以用setValuesForKeysWithDictionary方法对对象属性进行赋值,但是封装进字典的键一定要和类中的属性名相同,并且数量不能超过类中的属性数量