NSDictionary 通过唯一的key找到唯一的值
// 初始化 NSDictionary 是不可变的
NSDictionary *dic = [NSDictionary dictionaryWithObject:@"v" forKey:@"k"];
// 最常用的初始化方式
NSDictionary *dic = [NSDictionary
dictionaryWithObjectAndKeys:@"v",@"k",@"v",@"k",@"v",@"k",nil];
//
NSArray *keys = [NSArray arrayWithObjects:@"k1",@"k2","k3",nil];
NSDictionary *dic = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
[dic count] // 返回键值对数
isEqualTO... 比较键值对是否相同
objectForKey:@"k2" // 通过键取值 由于NSDictionary不可变所以只能取值不能改变值
//将字典写入到文件中
NSString *path = @"/Users/apple/Desktop/a.xml";
[dict writeToFile:path atomically:YES];
// 从文件中读取内容
dict = [NSDictionary dictionaryWithContentsOfFile:path];
[dict allKeys]; // 返回所有的key
// 根据多个key找到多个value
[dict objectsForKeys:[NSArray arrayWithObjects:@"k1",@"k2",nil]
notFoundMarker:@"not-found"];
//遍历字典
for(id key in dict) {
id value = [dict obj];
}
// 迭代遍历 key迭代器
NSEnumerator *enumer = [dict keyEnumerator];
id key = nil;
while(key = [enumer nextObject]){
id value = [dict objectForKey:key];
NSLog(@"%@=%@",key,value);
}
// 对象迭代器
[dict objectEnumerator];
// block 遍历
[dict enumerateKeysAndObjectsUsingBlock:(id key,id obj,BOOL *stop){
NSLog(@"");
}]
// 一个对象为字典的key或者value时,会做一次retain操作,计数器加1
当字典被销毁时,里面的所有key和value都会做一次release操作
====================================================
// 可变字典
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
Student *stu = ...
[dict setObject:stu forKey:@"k1"];
removeObjectForKey 删除所有键值对
removeObjectForKey:@"k1" 删除k1对应的元素
可以传数组删除多个key对应的元素 removeobjectForKeys
// 添加其他字典到当前字典
NSDictionary *other = [NSDictionary ictionaryWithObject:@"v2" forKey:@"k2"];
[dict addEntriesFromDictionary:other];
// 一个对象为字典的key或者value时,会做一次retain操作,计数器加1
当字典被销毁时,里面的所有key和value都会做一次release操作
联系客服