NSDictionary的初始化和一些常用的方法总结
NSDictionary
//初始化1。
NSDictionary *dic11=[[NSDictionary alloc] initWithObjects:@[@"qwe",@"asd",@"zxc",@"qaz",@"wsx"] forKeys:@[@"111",@"222",@"333",@"444",@"555"]];
//分别获取所有的键, 值
NSLog(@"%@",dic11.allKeys);
NSLog(@"%@",dic11.allValues);
//获取字典键值对总数
NSLog(@"%d",(dic11.count));
//字典遍历,快速枚举
for (id key in dic11) {
id value=[dic11 objectForKey:key];
NSLog(@"%@:%@",key,value);
}
//不可变字典一样可以字面常量初始化,key在前,value在后.
NSDictionary *dic00=@{@"keya":@"aaa",@"keyb":@111};
NSLog(@"%@",dic00);
//初始化的其他方法
//一个键值对字典的初始化
NSDictionary *dic1=[NSDictionary dictionaryWithObject:@"10001" forKey:@"000"];
//内容与dic1一样的字典初始化
NSDictionary *dic0=[NSDictionary dictionaryWithDictionary:dic1];
//多个键值对字典的初始化1
NSDictionary *dic2=[NSDictionary dictionaryWithObjects:@[@"11",@"22",@"33",@"44"] forKeys:@[@"first",@"second",@"third",@"four"]];
//多个键值对字典的初始化2
NSDictionary *dic3=[NSDictionary dictionaryWithObjectsAndKeys:@"湘小几把一号是逗帝",@"逗帝",@"娘一号",@"逗圣",@"祥几把",@"逗战圣佛",nil];
NSLog(@"%@",dic3[@"逗帝"]);
//建立一个内容与dic2一样的可变字典
NSMutableDictionary *dic4=[NSMutableDictionary dictionaryWithDictionary:dic2];
//插入一个键值对,有同名的,则覆盖原来的值
[dic4 setObject:@"jjj" forKey:@"jiji"];
NSLog(@"%@",dic4);
//插入某一个键值对,有同名的,则覆盖原来的值
[dic4 setObject:@"999" forKeyedSubscript:@"lan"];
[dic4 setObject:@"004" forKeyedSubscript:@"four"];
NSLog(@"%@",dic4);
//将dic1拼接到dic前面
[dic4 addEntriesFromDictionary:dic1];
NSLog(@"%@------",dic4);
//移除某一个键值对
[dic4 removeObjectForKey:@"third"];
NSLog(@"%@",dic4);
//将数组里的key对应的键值对移除
[dic4 removeObjectsForKeys:@[@"five",@"000"]];
NSLog(@"%@",dic4);
//将dic4原来的内容全部都替换成dic11的内容
[dic4 setDictionary:dic11];
NSLog(@"%@",dic4);
//将字典的内容保存到指定路径的文件中
[dic4 writeToFile:@"/Users/apple/Desktop/dic4.plist" atomically:YES];
//从指定路径中读取文件内容
NSDictionary *dic5=[NSDictionary dictionaryWithContentsOfFile:@"/Users/apple/Desktop/dic4.plist"];
NSLog(@"%@",dic5);
//dict3和dict2的内容完全相同,实质上是一个新的对象.
//字典的一种从指定路径文件获取内容的初始化方法。文件必须存在,不然内容是空的。
NSDictionary *dic6=[[NSDictionary alloc] initWithContentsOfFile:@"/Users/apple/Desktop/dic4.plist"];
NSLog(@"%@",dic6);
//移除所有键值对。
[dic4 removeAllObjects];
NSLog(@"%@",dic4);