《慕客网:IOS基础入门之Foundation框架初体验》学习笔记 <五> NSDicionary + NSMutableDictionary

 

 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 }

 

 
 1 int main(int argc, const char * argv[]) {
 2     @autoreleasepool {
 3         NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
 4         //添加键值对,直接添加就可以了
 5         [dict setObject:@"1" forKey:@"a"];
 6         [dict setObject:@"2" forKey:@"b"];
 7         [dict setObject:@"3" forKey:@"c"];
 8         NSLog(@"%@",dict);
 9         //删除键值对
10         [dict removeObjectForKey:@"a"];
11         NSLog(@"%@",dict);
12         //还可以通过传入数组对象,对应删除数组元素对应的所有键
13         [dict removeObjectsForKeys:[NSArray arrayWithObjects:@"a",@"c", nil]];
14         NSLog(@"%@",dict);
15     }
16     return 0;
17 }

 

 
posted @ 2015-07-22 22:24  何杨  阅读(244)  评论(0编辑  收藏  举报