首页 > 代码库 > NSDictionary
NSDictionary
一、#pragma mark 创建字典。
void dictionaryCreate() {
NSDictionary *dict = [NSDictionary dictionaryWithObject:@"v" forKey:@"k"];
dict = [NSDictionary dictionaryWithObjectsAndKeys:
@"v1",@"k1",
@"v2",@"k2",
@"v3",@"k3",nil];
NSArray *array1 = [NSArray arrayWithObjects:@"v1",@"v2",@"v3", nil];
NSArray *array2 = [NSArray arrayWithObjects:@"k1",@"k2",@"k3", nil];
dict = [NSDictionary dictionaryWithObjects:array1 forKeys:array2];
NSLog(@"%@",dict);
}
二、#pragma mark 字典基本用法。
void dictionaryUse() {
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
@"v1",@"k1",
@"v2",@"k2",
@"v3",@"k3",nil];
//count是计算有多少个键值对。
NSLog(@"count = %zi",dict.count);
//取出某键值对应的值。
id obj = [dict objectForKey:@"k2"];
NSLog(@"obj = %@",obj);
//将字典写入文件中。
NSString *path = @"/Users/jszx/Desktop/dict.xml";
NSString *path1 = @"/Users/jszx/Desktop/dict2.xml";
[dict writeToFile:path atomically:YES];
//从文件中读取内容到字典中。
NSDictionary *dict1 = [NSDictionary dictionaryWithContentsOfFile:path1];
NSLog(@"%@",dict1);
//返回所有的key
NSArray *keys = [dict allKeys];
NSLog(@"keys = %@",keys);
//返回所有的value值
NSArray *objects = [dict allValues];
NSLog(@"values = %@",objects);
//根据多个key取出对应的多个value,当key找不到对应的value时,用maker参数值代替。
objects = [dict objectsForKeys:[NSArray arrayWithObjects:@"k1",@"k2",@"k4", nil] notFoundMarker:@"not-found"];
NSLog(@"objects=%@",objects);
}
三、#pragma mark 遍历字典
void dictFor() {
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
@"v1", @"k1",
@"v2", @"k2",
@"v3", @"k3",nil];
//遍历字典的所有key
for (id key in dict) {
id value = http://www.mamicode.com/[dict objectForKey:key];
NSLog(@"%@=%@",key,value);
}
//迭代器遍历。
//key的迭代器
NSEnumerator *enumer = [dict keyEnumerator];
id key = nil;
while (key = [enumer nextObject]) {
id value = http://www.mamicode.com/[dict objectForKey:key];
NSLog(@"%@=%@",key,value);
}
//value的迭代器。
enumer = [dict objectEnumerator];
id value = http://www.mamicode.com/nil;
while (value = http://www.mamicode.com/[enumer nextObject]) {
NSLog(@"%@",value);
}
//block遍历。
[dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { NSLog(@"%@=%@",key,obj);}];
}
四、#pragma mark 字典内存管理
void dictMemory() {
Student *stu = [Student studentWithName:@"stu"];
Student *stu1 = [Student studentWithName:@"stu1"];
Student *stu2 = [Student studentWithName:@"stu2"];
//一个对象称为字典的key或者value时,会做一次retain操作。
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
stu, @"k1",
stu1, @"k2",
stu2, @"k3",nil];
//当字典被销毁时,里面的所有key和value都会做一次release操作。这里是用静态方法创建的字典,它会自动销毁。
}
NSDictionary