iOS学习、交流、进步

Objective-C的字典类NSDictionary

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

阅读更多
文章标签: objective-c NSDictionary
个人分类: Objective-C基础相关
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

Objective-C的字典类NSDictionary

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭