//key 和 value 都属于(id)对象类型
//key常用字符串NSString来表示
//存储数值型 一般可用 NSString
//int age ->@(age)
// [dic[name] intValue];
// @()-->转成NSNumber 类型
// intValue
//value可以使任意对象(NSString NSArrray , dog )
//NSDictionary 一旦创建不能修改增加删除
#pragma mark 字典的创建
NSDictionary * dic = [[NSDictionary alloc]initWithObjectsAndKeys:
@"value1",@"key1",
@"value2",@"key2",
@"value2",@"key3",nil];
NSLog(@"%@",dic);
NSDictionary * dic1 = [NSDictionary dictionaryWithObjectsAndKeys:@"value1",@"key1", nil];
//用字典创建字典
NSDictionary * dic2 = [[NSDictionary alloc]initWithDictionary:dic];
NSLog(@"%@",dic2);
//xcode4.6
//格式: key : value 多个元素之间用,分隔
//用NSLog打印字典是不支持汉字的转码
// \U5bd2\U4ed2;
NSDictionary * dic3 =
@{@"key1":@"value1",
@"key2":@"value2",
@"key3":@"value3",
@"key4":@"value2"
};
#pragma mark 查看键的个数
NSUInteger num = [dic2 count];
NSLog(@"%lu",num);
#pragma mark 通过key找value
NSString * str = [dic3 objectForKey:@"key1"];
//xcode4.6
NSString * str2 = dic3[@"key2"];
NSLog(@"%@",str);
NSLog(@"%@",str2);
#pragma mark 获取所有key 所有value
NSArray * keyArray = [dic3 allKeys];
NSArray * valueArray = [dic3 allValues];
NSLog(@"keys = %@",keyArray);
NSLog(@"values = %@",valueArray);
#pragma mark 查看一个value对应多个key
NSArray * array = [dic3 allKeysForObject:@"value2"];
NSLog(@"%@",array);
#pragma mark 可变字典
#pragma mark 创建可变字典
NSMutableDictionary * mutDic = [[NSMutableDictionary alloc] init];
NSDictionary * dic4 =
@{@"key1":@"value1",
@"key2":@"value2",
@"key3":@"value3",
@"key4":@"value2"
};
NSMutableDictionary * mutDic2 = [[NSMutableDictionary alloc]initWithDictionary:dic4];
#pragma mark 增加
//key不重复是增加键值对
[mutDic2 setObject:@"value3"
forKey:@"key5"];
//保证Key不重复 key必须唯一
//通过查询key的obj 是否为 ==NULL
// if ([mutDic2 objectForKey:@"key5"]== NULL) {
//
// }
NSDictionary * dic5 = @{@"key_1":@"value1",
@"key_2":@"value2"};
[mutDic2 addEntriesFromDictionary:dic5];
NSLog(@"%@",mutDic2);
#pragma mark 删除
//通过key删除值
[mutDic2 removeObjectForKey:@"key_1"];
NSLog(@"%@",mutDic2);
NSArray * array2 = @[@"key_2",@"key2",@"key4"];
[mutDic2 removeObjectsForKeys:array2];
NSLog(@"%@",mutDic2);
// [mutDic2 removeAllObjects];
// NSLog(@"%@",mutDic2);
#pragma mark 修改
//key 已存在是修改当前value的值
[mutDic2 setObject:@"hhhh" forKey:@"key1"];
NSLog(@"%@",mutDic2);
//完全覆盖掉当前字典中所有的值
[mutDic2 setDictionary:dic2];
NSLog(@"%@",mutDic2);
}