IOS ——OC—— NSDictionary的使用总结

键与值一一对应,键不能重复;
值可以重复;
1.NSDictionary的创建:(字典的内容是无序的,不能进行排序)
 NSDictionary *dic = [NSDictionary dictionary];//创建一个空字典
       
        NSDictionary *dic1 = [NSDictionary dictionaryWithObject:@"object" forKey:@"key"];//只有一对键值的字典
        NSLog(@"%@",dic1);
       
        NSDictionary *dic2 = [NSDictionary dictionaryWithObjectsAndKeys:@"value1",@"key1" ,@"value2",@"key2",nil];//字典的存放是无序的(没有下标的概念)(键值,键)
        NSLog(@"%@",dic2);
   
        NSDictionary *dic3 = @{
                               @"key1":@"123",
                               @"key2":@"456",
                               @"key3":@"466"
                               };//快速创建( @“键”:@“键值” )要用大括号!
        NSLog(@"%@",dic3);
        dic3 = @{@"1":@"hguf",
                  @"2":@"dfgdsf",
                  @"3":@"vbrthf"
                };//对dic3重新初始化,并没有改变内容;
1.NSDictionary的使用:
 long int count = dic3.count;//字典的长度,键值对个数:
        NSLog(@"%zi",count);
   
        NSString *s = [dic3 objectForKey:@"2"];//获取某key对应的值;
        NSLog(@"%@",s);
        NSString *s1 = dic3[@"3"];//获取某key对应的值;
        NSLog(@"%@",s1);
       
        //遍历:
        //获取key;
      NSArray *keyarr = [dic3 allKeys];
        for(NSString *key in keyarr)
 NSLog(@"%@=%@",key,dic3[key]);
1=hguf
2=dfgdsf
3=vbrthf
        //获取值
        NSArray *valuearr = [dic3 allValues];
        for(NSString *value in valuearr)
            NSLog(@"%@",value);
   
hguf
dfgdsf
vbrthf
 
        NSEnumerator *e = [dic3 keyEnumerator];//先获取字典中key的枚举器,然后遍历该枚举器,获取key对应的值
        id k;
        while(k=[e nextObject])
            NSLog(@"%@ = %@",k,dic3[k]);
1 = hguf
2 = dfgdsf
3 = vbrthf
 
      NSEnumerator *e1 = [dic3 objectEnumerator];//获取字典中值的枚举器
        id value;
        while(value=[e1 nextObject])
 结果:           NSLog(@"%@",value);
hguf
dfgdsf
vbrthf
       
        [dic3 enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {          NSLog(@"key=%@,value=%@",key,obj);
        }];//stop代表遍历停止
   运行结果:
key=1,value=hguf
key=2,value=dfgdsf
key=3,value=vbrthf
posted @ 2015-04-07 18:13  #零下一度&  阅读(716)  评论(0编辑  收藏  举报