NSDictionary和NSMutableDictionary

/NSDictionary/

//内容可以是任意的对象指针 //内容是一些键值对 key value //必须成对出现 一个 key 对应一个 value //key 是唯一的 不能出现多个相同的 key

创建一个不可变字典(1)

NSDictionarydict=[[NSDictionary alloc]initWithObjectsAndKeys:@"1",@"one",@"2",@"two",@"3",@"three",@"4", @"four",@"5",@"five", nil];//
创建一个不可变字典(2)
NSDictionary * dict1 = [NSDictionary dictionaryWithDictionary:dict]; 创建一个不可变字典(3)
NSArray * values =[[NSArray alloc]initWithObjects:@"1",@"2",@"3",@"4", nil]; NSArray
keys=[[NSArray alloc]initWithObjects:@"one",@"two",@"three",@"four", nil];
NSDictionary* dict2 = [[NSDictionary alloc]initWithObjects:values forKeys:keys];
//键值对的个数
NSLog(@"count = %ld",[dict2 count]);
//查找 通过 key 找到对应值
NSLog(@"%@",[dict objectForKey:@"four"]); 词典类的存在就是为了解决在大量数据中查找方便,因为它是通过 key 直接找到 value 所以速度很快,避免一个个的遍历寻找造成的效率低下,善用字典类会帮 你的程序提速。
//创建 key 的枚举器
NSEnumerator * keyenumer = [dict keyEnumerator]; while (obj = [keyenumer nextObject]) {
NSLog(@"obj = %@",obj); }
//快速枚举枚举的是 key for (id od in dict) {
NSLog(@"od = %@",od); }

/NSMutableDictionary/

NSMutableDictionary 是NSDictionary的子类,所以继承了NSDictionary的方法。

创建可变字典

NSMutableDictionarydict=[[NSMutableDictionary alloc]initWithObjectsAndKeys:@"1",@"one",@"2",@"two",@"3",@"three",@"4", @"four", nil];
NSMutableDictionary
dict1 =[NSMutableDictionary dictionaryWithCapacity:10] : 创建一个可变词典初始指定它的长度为 10.,动态的添加数据如果超过 10 这个 词典长度会自动增加,所以不用担心数组越界。
//增加 删除 修改
[dict setObject:@"5" forKey:@"five"];//字典中不存在@“five”key 那么就是增 加键值对
[dict setObject:@"7" forKey:@"one"];//字典中存在@“one”key 那么就是修改@ “one”对应的值
[dict removeObjectForKey:@"one"];//删除键值对

  • (void)removeAllObjects;//删除所有键值对
  • (void)removeObjectsForKeys:(NSArray *)keyArray;//删除keys 数组对应的键值对
  • (void)setDictionary:(NSDictionary *)otherDictionary;//修 改字典

//字典可以创建成plist文件
[dic writeToFile:@"/Users/apple/Desktop/b.txt" atomically:YES];
//读出来
NSDictionary *dic1 = [[NSDictionary alloc]initWithContentsOfFile:@"/Users/apple/Desktop/b.txt"];

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容