标签:
1 /** 2 OC中 JAVA中 3 NSArray List 4 NSSet Set 5 NSDictionary Map 6 7 集合 8 1.NSArray\NSMutableArray 9 * 有序 10 * 快速创建(不可变):@[]; 11 * 快速访问元素:数组名[i]; 12 13 2.NSSet\NSMutableSet 14 * 无序 15 16 3.NSDictionary\NSMutableNSMutable 17 * 无序 18 * 快速创建(不可变):@{key1 : value1, key2 : value2} 19 * 快速访问元素:字典名[key]; 20 */ 21 22 23 #import <Foundation/Foundation.h> 24 25 int main(int argc, const char * argv[]) { 26 @autoreleasepool { 27 28 /** 29 key ---> value 键值对 30 索引 ---> 文字内容 31 */ 32 /** 字典的创建方式1 */ 33 NSDictionary *dict1 = [NSDictionary dictionaryWithObject:@"Chris Paul" forKey:@"name"]; 34 id obj1 = [dict1 objectForKey:@"name"]; 35 NSLog(@"%@", obj1); 36 37 /** 字典的创建方式2 */ 38 NSArray *keys1 = @[@"name", @"address"]; 39 NSArray *objects = @[@"Chris Paul", @"Los Angeles"]; 40 NSDictionary *dict2 = [NSDictionary dictionaryWithObjects:objects forKeys:keys1]; 41 id obj2 = [dict2 objectForKey:@"address"]; 42 NSLog(@"%@", obj2); 43 44 /** 字典的创建方式3 */ 45 NSDictionary *dict3 = [NSDictionary dictionaryWithObjectsAndKeys:@"Chris Paul", @"name", @"Los Angeles", @"Address", nil]; 46 id obj3 = [dict3 objectForKey:@"name"]; 47 NSLog(@"%@", obj3); 48 49 /** 字典的创建方式4:快速创建(Xcode新特性)*/ 50 NSDictionary *dict4 = @{@"name" : @"Chris Paul", @"address" : @"Los Angeles"}; /** @{@“id objec” : id, ... }返回值是NSDictionary */ 51 id obj4 = dict4[@"address"]; /** 此方法又是Xcode的新特性 */ 52 NSLog(@"%@", obj4); 53 54 /** 字典键值对的访问 */ 55 NSLog(@"%ld", dict4.count); 56 57 /** 可变字典的创建 */ 58 NSMutableDictionary *dict5 = [NSMutableDictionary dictionary]; 59 [dict5 setObject:@"Chris Paul" forKey:@"name"]; /** 添加键值对 */ 60 [dict5 setObject:@"Los Angeles" forKey:@"address"]; /** 添加键值对 */ 61 [dict5 setObject:@"Magic Johnson" forKey:@"name"]; /** 此时,会覆盖Chris Paul*/ 62 NSLog(@"%@", dict5[@"name"]); 63 [dict5 removeObjectForKey:@"address"]; /** 移除键值对 */ 64 NSLog(@"%@", dict5[@"address"]); 65 66 /** 字典的遍历方法1 */ 67 NSDictionary *dict6 = @{@"name" : @"Chris Paul", 68 @"address" : @"Los Angeles", 69 @"name2" : @"Chris Paul"}; 70 /** 注意: 71 1.字典不允许有相同的key,但允许有相同的value(object) 72 2.字典是无序的 73 */ 74 NSArray *keys2 = [dict6 allKeys]; /** 这个方法打印出来是乱的 */ 75 NSLog(@"%@", keys2); 76 for (int i = 0; i<dict6.count; i++) { 77 NSString *key = keys2[i]; 78 NSString *object = dict6[keys2]; 79 NSLog(@"%@---%@", key, object); 80 } 81 82 /** 字典的遍历方法2:block */ 83 [dict6 enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { 84 NSLog(@"%@---%@", key, obj); 85 }]; 86 } 87 return 0; 88 }
标签:
原文地址:http://www.cnblogs.com/herui1991/p/4733343.html