1、NSDictionary (不可变字典)
字典的初始化
//一个key - value
NSDictionary *dic1 = [NSDictionary dictionaryWithObject:@"@123" forKey:@"key1"];
//两个以上 key - value
NSDictionary *dic2 = [NSDictionary dictionaryWithObjectsAndKeys:@"value1",@"key1",@"value2",@"key2" ,nil];
//用字典为另一个子字典初始化
NSDictionary *dic3 = [NSDictionary dictionaryWithDictionary:dic1]
//新方法赋值
NSDictionary *dic4 = @{@"key1": @"value1",@"key2": @"value2"};
//以为件内容初始化一个字典
NSDictionary *dic5 = [NSDictionary dictionaryWithContentsOfFile:path];
//将字典的key转成一个枚举对象,用于遍历
NSEnumerator *enumerator = [dic4 keyEnumerator];
字典的常用方法
//返回字典键值对的个数
NSInteger count = [dic4 count];
//通过key获取对应的value对象
NSObject *object = [dic2 objectForKey:@"key1"];
//获取所有键的集合
NSArray *keys = [dic3 allKeys];
//获取所有值的集合
NSArray *values = [dic3 allValues];
1、NSMutableDictionary (可变字典,继承自NSDictionary)
可变字典与不可变字典的初始化方法相同,但不能用新方法。下面只介绍常用方法
常用方法
NSMutableDictionary *dic6 = [NSMutableDictionary dictionary];
//像字典中追加一个新的 key5 和 value5
[dic6 setObject:@"value5" forKey:@"key5"];
//像字典中添加整个字典对象
[dic6 addEntriesFromDictionary:dic1];
//将字典6的对象内容设置与字典1的对象内容相同
[dic6 setDictionary:dic1];
//删除键所对应的键值对
[dic6 removeObjectForKey:@"key1"];
//删除数组中的所有key 对应的键值对
NSArray *array = @[@"key1",@"key2",@"key3"];
[dic6 removeObjectsForKeys:array];
//移除字典中的所有对象
[dic6 removeAllObjects];
遍历字典
一般遍历
for (int i = 0; i < [dic3 count]; i++) {
id key = [keys objectAtIndex:i];
id obj = [dic3 objectForKey:key];
NSLog(@"%@",obj);
}
快速遍历
for (id key in dic3) {
id obj = [dic3 objectForKey:key];
NSLog(@"%@",obj);
}
枚举的办法遍历
NSEnumerator *enumerator = [dic4 keyEnumerator];
id key = [enumerator nextObject];
while (key) {
id obj = [dic4 objectForKey:key];
NSLog(@"%@",obj);
key = [enumerator nextObject];
}
来源:oschina
链接:https://my.oschina.net/u/1245365/blog/177736