标签:
------<a href="http://www.itheima.com" target="blank">Java培训、Android培训、iOS培训、.Net培训</a>、期待与您交流! -------
1 #import <Foundation/Foundation.h> 2 3 4 /* 5 字典: 6 key-->value 7 索引-->文字内容 8 9 里面存储的东西都是键值对 10 11 12 */ 13 14 int main() { 15 //不可变,初始化需完成赋值 16 NSDictionary *dict = [NSDictionary dictionaryWithObject:@"jack" forKey:@"name"]; 17 18 id obj = [dict objectForKey:@"name"]; 19 20 NSLog(@"%@", obj); 21 22 23 NSArray *keys = @[@"name",@"address"]; 24 NSArray *objects = @[@"jack", @"北京"]; 25 26 NSDictionary *dict2 = [NSDictionary dictionaryWithObjects:objects forKeys:keys]; 27 id obj1 = [dict2 objectForKey:@"name"]; 28 29 NSLog(@"%@", obj1); 30 31 32 NSDictionary *dict3 = [NSDictionary dictionaryWithObjectsAndKeys:@"jack", @"name", 33 @"北京", @"address", 34 @"34234234", @"qq", nil]; 35 36 id obj2 = [dict3 objectForKey:@"qq"]; 37 38 NSLog(@"%@", obj2); 39 40 41 //建议使用 42 NSDictionary *dict4 = @{@"name" : @"jack", 43 @"address" : @"北京", 44 @"qq" : @"4234234"}; 45 46 //id obj3 = [dict4 objectForKey:@"address"]; 47 48 //建议使用 49 id obj3 = dict4[@"address"]; 50 51 NSLog(@"%@", obj3); 52 53 //返回键值对的个数 54 NSLog(@"%ld", dict4.count); 55 56 57 58 59 //可变字典 60 NSMutableDictionary *dict5 = [NSMutableDictionary dictionary]; 61 //添加键值对,无序 62 [dict5 setObject:@"jack" forKey:@"name"]; 63 [dict5 setObject:@"北京" forKey:@"address"]; 64 65 //重复给key赋值会覆盖以前的值,字典不允许相同的key,允许有相同的object 66 [dict5 setObject:@"rose" forKey:@"name"]; 67 68 //删除键值对 69 //[dict5 removeObjectForKey:@"name"]; 70 71 72 //遍历 73 NSDictionary *dict6 = @{@"name" : @"tom", 74 @"address" : @"北京", 75 @"tel" : @"3423424"}; 76 // NSArray *Keys = [dict6 allKeys]; 77 // 78 // for (int i = 0; i<dict6.count; i++) { 79 // 80 // NSString *key = Keys[i]; 81 // NSString *object = dict6[key]; 82 // NSLog(@"%@=%@", key, object); 83 // } 84 85 //block遍历 86 [dict6 enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { 87 NSLog(@"%@-%@", key, obj ); 88 89 *stop = YES; 90 91 }]; 92 93 return 0; 94 }
标签:
原文地址:http://www.cnblogs.com/xbl-hm/p/4953638.html