首页 > 代码库 > oc中字典的实现方法详解

oc中字典的实现方法详解

一:字典的基本概念

Foundation中的字典(NSDictionary,NSMutableDictionary)是由键-值对组成的数据集合.正如,我们在字典里查找单词的定义一样.

通过key(键),查找的对应的value(值),key通常是字符串对象,也可以是其他任意类型对象.在一个字典对象中,key的值必须是唯一的.

此外,字典对象的键和值不可以为空(nil),如果需要在字典中加入一个空值,可以加入NSNull对象

二:不可变字典-NSDictionary

1:初始化(以一个元素和多个元素进行初始化):

//以一个键值对象 进行初始化

    NSDictionary *dic=[NSDictionary dictionaryWithObject:@"卢灿小样" forKey:@"lucan"];     NSLog(@"%@",dic);     NSLog(@"%@",[dic objectForKey:@"lucan"]);    //输出dic键值对个数    NSLog(@"%d",dic.count);        //用多种方法创建键值对    NSDictionary *dic1=[NSDictionary dictionaryWithObject:@"卢灿实验2号" forKey:@"小样"];    NSLog(@"%@",[dic1 objectForKey:@"小样"]);        NSDictionary *dic2=@{@"first":@"2301",@"sec":@"2034"};    NSDictionary *dic3=[NSDictionary dictionaryWithObjectsAndKeys:@"刘湘",@"name",@"小样",@"name1", nil];    //输出结果    NSLog(@"  ----%@%@",dic2,dic3);       //数组把vaule和key放到一个可变数组    NSArray *values=@[@123,@668,@345];    NSArray *key=@[@"first",@"swcond",@"third"];    NSDictionary *dic4=[NSDictionary dictionaryWithObject:values forKey:key];    NSLog(@"xxxxxxxxxxxx%@",dic4);        //排序    NSArray *arry=[dic4 keysSortedByValueUsingSelector:@selector(compare:)];    NSLog(@"+++++++%@",arry);    //用一个现有字典对象初始化另一个新字典对象(创建可变对象)    NSDictionary *arry1=[[NSDictionary alloc]initWithDictionary:dic4 ];    NSLog(@"ooooooo%@",arry1);        //保存对象到内容文件    NSString *path=@"/Users/apple/Desktop/test.plist";    [dic2 writeToFile:path atomically:YES];        //从以前保存的文件读取到字典对象    NSDictionary *data=http://www.mamicode.com/[NSDictionary dictionaryWithContentsOfFile:path];    NSLog(@"xxxxx%@",data);        //字典的遍历key1相当于a[i]中的i,dic4就自己定义的字典    for (id key1 in dic4) {        id vaule=[dic4 objectForKey:key1];        NSLog(@"qqqqqq%@%@",key,vaule);    }    //- (void)removeObjectForKey:(id)aKey;    //删除键值对    NSMutableDictionary  *dic7=[NSMutableDictionary dictionaryWithDictionary:dic2];    [dic7 removeObjectForKey:@"sec"];    NSLog(@"%@",dic7);       // 判断key值有就替换没有就添加    [dic7 setObject:@"3412" forKey:@"sec"];    NSLog(@"%@",dic7);        //增加dic4  字典无顺序    [dic7 addEntriesFromDictionary:dic4];    NSLog(@"%@",dic7);