// ********************不可变最字典*****************
/* NSDictionary * dic = [NSDictionary dictionaryWithObject:@"张三" forKey:@"name" ];
NSLog(@"%@", dic);//便利构造器创建字典
//字典里一个key只有一个vlaue, 但是一个value可以有好几个key
NSDictionary * dic1 = [[NSDictionary alloc] initWithObjectsAndKeys:@"zhangsan", @"name", @"boy", @"sex", @"toyke", @"address", nil];//初始化创建字典
NSLog(@"%@", dic1);
NSArray * value = [[NSArray alloc] initWithObjects:@"张三", @"李四", @"王五", @"赵六", nil];
NSArray * key = [[NSArray alloc] initWithObjects:@"name3", @"name4", @"name5", @"name6", nil];
NSDictionary * nk = [[NSDictionary alloc] initWithObjects:value forKeys:key];//初始化+数组创建字典
NSLog(@"%@", nk);
NSLog(@"%lu", [nk count]);//获取键值对的个数
NSString * result = [nk objectForKey:@"name3"];//根据键来获得相对应的值
NSLog(@"%@", result);
NSString * re = [nk objectForKey:@"name6"];
NSString * re1 = [nk objectForKey:@"name4"];
NSString * re3 = [nk objectForKey:@"name5"];
NSLog(@"%@, %@, %@", re, re1, re3);
NSArray * cou = [nk allKeys];//获得所有的键
for (int i = 0; i < [cou count]; i++) {
NSString * key = [cou objectAtIndex:i];//获得数组中的键
NSString * value = [nk objectForKey:key];//用键来获得值
NSLog(@"%@", value);
}
NSArray * cou1 = [nk allKeys];
for (int i = 0; i < [cou1 count]; i++) {
NSLog(@"%@", [nk objectForKey:[cou objectAtIndex:i]]);
}
NSArray * values = [nk allValues];//获得所有的值存放在数组中
for (int i = 0; i < [values count]; i++) {
id c = [values objectAtIndex:i];
NSLog(@"%@", c);
}*/
// ********************可变最字典*****************
NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:1];
[dict setObject:@"zhangsan" forKey:@"name"];
[dict setObject:@"boy" forKey:@"sex"];
[dict setObject:@"18" forKey:@"age"];
NSLog(@"%@", dict);
[dict setObject:@"paoniu" forKey:@"hobby"];
NSLog(@"%@", dict);
NSDictionary * dic1 = [[NSDictionary alloc] initWithObjectsAndKeys:@"zhangsan1", @"name1", @"boy1", @"sex1", @"toyke1", @"address", nil];//初始化创建字典
[dict setValuesForKeysWithDictionary:dic1];
[dict removeObjectForKey:@"name1"];//移除键值为name1的值
NSNumber * num = [NSNumber numberWithInt:24];//用number把数字转成对象
[dict setObject:num forKey:@"age"];
NSNumber * score = [NSNumber numberWithFloat:88.8];
[dict setObject:score forKey:@"score"];
[dict setObject:[NSNumber numberWithDouble:999.999] forKey:@"fight"];
NSLog(@"%@", dict);
float sco = [[dict objectForKey:@"score"] floatValue];//把对象转成基本数据类型
NSLog(@"%g", sco);
原文地址:http://www.cnblogs.com/MRJ1101/p/3807832.html