关闭

Objective-C的字典类NSDictionary

标签: objective-cNSDictionary
765人阅读 评论(0) 收藏 举报
分类:

1.初始化

//初始化一组数组,存入字典中作为关键字
NSNumber *num = [NSNumber numberWithInt:100];
NSDictionary *dic1 = [NSDictionary dictionaryWithObject:num forKey:@"key1"];

//初始化多组数据
NSDictionary *dic2 = [NSDictionary dictionaryWithObjectsAndKeys:@"hello",@"key2",@"world",@"key3",@"csdn",@"key4", nil];

//用一个字典初始化另外一个字典
NSDictionary *dic3 = [NSDictionary dictionaryWithDictionary:dic2];

//打印输出
NSLog(@"dic1 :  %@,dic2  :  %@,  dic3   :   %@",dic1,dic2,dic3);
输出:dic1 :{

    key1 = 100;

},dic2  :  {

    key2 = hello;

    key3 = world;

    key4 = csdn;

},  dic3   :   {

    key2 = hello;

    key3 = world;

    key4 = csdn;

}

2.获取字典的值
//获取长度
int length = [dic2 count];
NSLog(@"dic2 length = %d",length);

//根据key获取key所对应的value
NSLog(@"key3 value = %@",[dic2 objectForKey:@"key3"]);

//可以获取所有的keys
NSArray *allkeys =  [dic3 allKeys];
NSLog(@"NSarray allkey = %@",allkeys);

//可以获取所有的values
NSArray *allvalues =  [dic3 allValues];
NSLog(@"NSarray allvalues = %@",allvalues);
输出:dic2  length = 3

     key3 value = world

     NSarray allkey = (

          key4,

          key3,

          key2

     )

     NSarray allvalues = (

          csdn,

          world,

          hello

     )

3.可变字典
//----- 初始化
NSMutableDictionary *dic4 = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"one",@"key4",@"two",@"key5", nil];

//定义成空字典
NSMutableDictionary *dic5 = [NSMutableDictionary dictionary];
        
//将字典dic2整体添加到dic4钟
[dic4 addEntriesFromDictionary:dic2];

//添加一个元素
[dic4 setValue:@"three" forKey:@"key6"];

//根据key获取value
NSLog(@"key6 =  %@",[dic4 objectForKey:@"key6"]);
4.字典的遍历
(1)一般遍历
NSArray *keys4 = [dic4 allKeys];
        
for(int i=0;i<[dic4 count];i++)
{
        
    NSLog(@"dic4 key = %@,value=%@",[keys4 objectAtIndex:i],[dic4 objectForKey:[keys4 objectAtIndex:i]]);
}
输出:dic4 key = key3,value=world

     dic4 key = key6,value=three

     dic4 key = key4,value=csdn

     dic4 key = key2,value=hello

     dic4 key = key5,value=two

(2)高效的for遍历
for (NSString *key in dic4)
{
     NSLog(@"dic4 key = %@ ,value = %@",key,[dic4 objectForKey:key]);
}
输出:dic4 key = key3,value=world

     dic4 key = key6,value=three

     dic4 key = key4,value=csdn

     dic4 key = key2,value=hello

     dic4 key = key5,value=two

(3)枚举遍历
NSEnumerator *enum1 = [dic4 keyEnumerator];
//获取key,如果不为空,则进行偏移
id key = [enum1 nextObject];
while (key) 
{          
    NSLog(@"key = %@ ,value = %@ ",key,[dic4 objectForKey:key]);
            
    key = [enum1 nextObject];
}

输出:dic4 key = key3,value=world

     dic4 key = key6,value=three

     dic4 key = key4,value=csdn

     dic4 key = key2,value=hello

     dic4 key = key5,value=two

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:58405次
    • 积分:1128
    • 等级:
    • 排名:千里之外
    • 原创:55篇
    • 转载:3篇
    • 译文:0篇
    • 评论:11条
    最新评论