Objective-C中字典类
字典是用于保存具有映射关系(key-value对)的数据集合.一个key-value对认为是一个条目(Entry),字典是存储key-value对的容器.
字典类的特点
与数组不同,字典靠key存取元素;
key值不能重复,value必须是对象;
键值对在字典中是无序存储的.
字典分为不可变字典(NSDictionary)和可变字典(NSMutableDictionary).
不可变字典(NSDictionary)
字典一旦创建,键值对不可更改,不可添加, 不可删除.
仅能读取key或value.
创建字典对象
1 NSDictionary *dic1 = [NSDictionary dictionaryWithObject:@"张三" forKey:@"name"]; 2 NSLog(@"dic1 %@", dic1);
创建有多个key-value对的字典
1 NSDictionary *dic2 = [NSDictionary dictionaryWithObjectsAndKeys:@"a", @"1", @"b", @"2", @"c", @"3", nil]; 2 NSLog(@"dic2 %@", dic2); 3 //获取所有的key 4 NSLog(@"key %@", dic2.allKeys); 5 // 获取所有的value 6 NSLog(@"value %@", dic2.allValues); 7 // 通过key 找 value 8 // 根据key获取对应value 9 NSLog(@"object %@", [dic2 objectForKey:@"2"]);
可变字典(NSMutableDictionary)
创建可变字典
1 NSMutableDictionary *mDic = [NSMutableDictionary dictionary]; 2 [mDic setObject:@"lilei" forKey:@"name"]; 3 [mDic setObject:@"m" forKey:@"sex"]; 4 NSLog(@"mDic %@", mDic);
添加/修改key-value对
1 // 当key不存在的时候 添加key-value对 2 // 当key存在的时候 找到对应的key 替换对应value内容 3 [mDic setObject:@"lilei" forKey:@"name"]; 4 [mDic setObject:@"male" forKey:@"sex"]; 5 NSLog(@"mDic %@", mDic); 6 // 修改 7 [mDic setObject:@"hanmeimei" forKey:@"name"]; 8 NSLog(@"mDic %@", mDic);
删除字典
1 // 删除 2 [mDic removeObjectForKey:@"name"]; 3 NSLog(@"mDic %@", mDic);
遍历字典
1 // 遍历字典 2 NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"lilei", @"name", @"male", @"sex", @"18", @"age", nil]; 3 NSLog(@"dic %@", dic); 4 NSArray *arr1 = dic.allKeys; 5 for (NSInteger i = 0; i < arr1.count; i++) { 6 // 获取每一个key值 7 NSString *key = [arr1 objectAtIndex:i]; 8 // 根据key获取对应value 9 NSLog(@"key: %@, value: %@", key, [dic objectForKey:key]); 10 }