1 #import <Foundation/Foundation.h> 2 3 int main(int argc, const char * argv[]) 4 { 5 @autoreleasepool 6 { 7 /* 8 字典: 9 存储的内存不是连续的 10 用key和value进行对应(键值) 11 kvc 键值编码 12 */ 13 NSDictionary *dict1 = [NSDictionary dictionaryWithObject:@"1" forKey:@"a"]; 14 NSLog(@"dict1 = %@", dict1); 15 16 NSDictionary *dict2 = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"1", @"2", @"3", nil] forKeys:[NSArray arrayWithObjects:@"a", @"b", @"c", nil]]; 17 NSLog(@"dict2 = %@", dict2); 18 19 NSDictionary *dict3 = @{@"1":@"a", @"2":@"b"};//1, 2 代表key,a, b 代表value 20 NSLog(@"dict3 = %@", dict3); 21 int count = (int)[dict2 count]; 22 NSLog(@"count = %d", count); 23 24 NSString *value1 = [dict2 valueForKey:@"b"]; 25 NSLog(@"value1 = %@", value1); 26 27 NSString *value2 = [dict2 objectForKey:@"b"]; 28 NSLog(@"value2 = %@", value2); 29 30 NSArray *allValues = [dict2 allValues]; 31 NSLog(@"allValues = %@", allValues); 32 NSArray *allKey = [dict2 allKeys]; 33 NSLog(@"allKey = %@", allKey); 34 35 NSArray *array = [dict2 objectsForKeys:[NSArray arrayWithObjects:@"a", @"b", @"d", nil] notFoundMarker:@"not fount"]; 36 NSLog(@"array = %@", array); 37 38 //遍历字典 39 for(NSString *key in dict2) 40 { 41 NSLog(@"%@ = %@", key, [dict2 objectForKey:key]); 42 } 43 for(id object in dict2) 44 { 45 NSLog(@"%@ = %@", object, [dict2 objectForKey:object]); 46 } 47 //用枚举器遍历 48 NSEnumerator *en = [dict2 keyEnumerator]; 49 id key = nil; 50 while (key = [en nextObject]) 51 { 52 NSLog(@"key - %@", key); 53 } 54 #pragma mark - NSMutableDictionary 55 NSMutableDictionary *dictM = [[NSMutableDictionary alloc] init]; 56 //添加键值对 57 [dictM setValue:@"1" forKey:@"a"]; 58 [dictM setValue:@"2" forKey:@"b"]; 59 NSLog(@"dictM = %@", dictM); 60 //删除键值对 61 // [dictM removeAllObjects]; 62 // [dictM removeObjectForKey:@"b"]; 63 [dictM removeObjectsForKeys:[NSArray arrayWithObjects:@"a", @"b", nil]]; 64 NSLog(@"dictM = %@", dictM); 65 66 } 67 return 0; 68 }