标签:
1 int main(int argc, const char * argv[]) { 2 @autoreleasepool { 3 //字典, 存储的内存不是连续的 用key和value进行对应(键值) 4 //kvc 键值编码 5 NSDictionary *dic = [NSDictionary dictionaryWithObject:@"1" forKey:@"a"]; 6 NSLog(@"%@",dic);//以上的方法是不常用的 7 //注意两个参数是数组 8 //NSDictionary *dic2 = [NSDictionary dictionaryWithObjects:<#(NSArray *)#> forKeys:<#(NSArray *)#>] 9 //所以还是要先创建两个数组 10 NSArray *array1 = [[NSArray alloc] initWithObjects:@"a",@"b",@"c",@"d", nil]; 11 NSArray *array2 = [[NSArray alloc] initWithObjects:@"1",@"2",@"3",@"4", nil]; 12 NSDictionary *dic2 = [[NSDictionary alloc] initWithObjects:array1 forKeys:array2]; 13 NSLog(@"%@",dic2); 14 // 15 NSDictionary *dic3 = @{@"m":@"9",@"n":@"8"}; 16 NSLog(@"%@",dic3); 17 //输出字典的长度 18 int count = (int)[dic3 count]; 19 NSLog(@"%d",count); 20 //通过键 获得 值 21 NSString *str = [dic3 valueForKey:@"m"];//或者[dic3 objectForKey:@"m"] 22 NSLog(@"%@",str); 23 //获取所有键值中的键和值 24 NSArray *allValue = [dic3 allValues]; 25 NSArray *allKey = [dic3 allKeys]; 26 //通过多个键找值,因为是多个,当然返回的是数组 27 NSArray *array = [dic2 objectsForKeys:[NSArray arrayWithObjects:@"2",@"3",@"9", nil] notFoundMarker:@"not found"]; 28 NSLog(@"%@",array); 29 //遍历字典,数组通过下标遍历,字典当然通过key来遍历 30 for (NSString *key in dic2) { 31 NSLog(@"%@ = %@",key,[dic2 objectForKey:key]); 32 } 33 //使用针对字典的枚举器 34 NSEnumerator *en = [dic2 keyEnumerator]; 35 id key = nil; 36 while (key = [en nextObject]) { 37 NSLog(@"key - %@",key); 38 } 39 //还有一个block方法,用法都是一样的 40 /* 41 [dic2 enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { 42 43 }];*/ 44 } 45 return 0; 46 }
《慕客网:IOS基础入门之Foundation框架初体验》学习笔记 <五> NSDicionary
标签:
原文地址:http://www.cnblogs.com/goodboy-heyang/p/4668861.html