/**
NSDictionary
创建不可变字典对象
[,,,] 数组 ()
字典 元素的一般形式 key:value 键值对
@{key:value,@"one":@"1",[NSDate Date]:@"1"};
通常key为字符串
字典没有顺序
dict1 @{@"frames":@{1:@{}, 2: @{} }, @"metadata":@{} }
dict2 = dict1[@"frames"]
*/
1构造字典 key:value
NSDictionary *dict = @{@"key":@"value",@"one":@"1",@"two":@"2"};
NSLog(@"dict= %@",dict);
2 用传入的value和key构造字典
先输入value再输入key
NSDictionary * dict1 = [[NSDictionary alloc]initWithObjectsAndKeys:@"value",@"key",@"1",@"one",@"2",@"two", nil];
NSLog(@"dict1 = %@",dict1);
3 用传入的字典构造字典
NSDictionary *dict2 = [[NSDictionary alloc]initWithDictionary:dict1];
NSLog(@"dict2 = %@",dict2);
4 用传入的key数组 和value数组构造字典
NSArray *keys = @[@"key",@"one",@"two"];
NSArray *values = @[@"value",@"1",@"2"];
NSDictionary *dict3 = [[NSDictionary alloc]initWithObjects:values forKeys:keys];
NSLog(@"dict3 = %@",dict3);
/**************类方法 创建字典对象********************/
//传入的value和key进行构造字典
NSDictionary *dict4 = [NSDictionary dictionaryWithObjectsAndKeys:@"value",@"key",@"1",@"one",@"2",@"two", nil];
NSLog(@"dict4 = %@",dict4);
//传入字典创建字典
NSDictionary *dict5 = [NSDictionary dictionaryWithDictionary:dict4];
NSLog(@"dict4 = %@",dict5);
//用key数组和value数组创建字典
NSDictionary *dict6 = [NSDictionary dictionaryWithObjects:values forKeys:keys];
NSLog(@"dict6 = %@",dict6);
// 创建只有一个键值对的字典对象
NSDictionary * dict7 = [NSDictionary dictionaryWithObject:@"1" forKey:@"one"];
NSLog(@"dict7 = %@",dict7);
字典的操作
字典的key是唯一的 value值可以重复 one = 1 two = 1
添加已经存在的key 对应的value会被后面传入的覆盖]
//1 获取键值对的个数
NSDictionary *dict = @{@"one":@"1",@"two":@"2",@"three":@"3",@"four":@"4",@"five":@"5"};
NSUInteger count = [dict count];
//2 通过key值获取value
// dict[@"key"];
id obj = [dict objectForKey:@"one"];
NSLog(@"obj = %@",obj);
//3 获取全部的key
NSArray *keyArray = [dict allKeys];
NSLog(@"keys = %@",keyArray);
//4 获取值对应的所有key
NSArray *array = [dict allKeysForObject:@"1"];
NSLog(@"array = %@",array);
//5 获取所有的value
NSArray *ValueArray = [dict allValues];
NSLog(@"values = %@",ValueArray);
//6 判断两个字典是否相等
BOOL ret = [dict isEqualToDictionary:@{@"one":@"1"}];
if (ret == 0)
{
NSLog(@"两个字典不相等");
}
// 7 字典的遍历
NSUInteger len = [dict count];
NSArray *keyArrays = [dict allKeys];
for (NSInteger i= 0; i<len; i++)
{
NSLog(@"%@ : %@",keyArrays[i],[dict objectForKey:keyArrays[i]]);
}
// 枚举key
NSEnumerator *keyEnum = [dict keyEnumerator];
id key = nil;
while (key = [keyEnum nextObject])
{
NSLog(@"%@ : %@",key, dict[key]);
}
//for-in遍历
for (id key in dict)
{
NSLog(@"%@:%@",key,dict[key]);
}