NSDictionary/NSMutableDictionary
Posted cindyli
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了NSDictionary/NSMutableDictionary相关的知识,希望对你有一定的参考价值。
NSDictionary/NSMutableDictionary 特点:
(1)里存储的东西都是键值对
(2)可以像数组一样快速创建(适用 NSDictionary):@{key1 : value1,
(3)快速访问元素:字典名 [key]
比如可以这样为指定 key 赋值:
dic [@”key1”] = @”value1”;
快速获取 key 所对应的 value:
key2 : value2}
NSString *name = dic[@”name”];//存储的是 String
或者:
NSDictionary *userdic = dic[@”user”];//存储的是 NSDictionary
NSString *name = userdic [@”name”];
(4)字典不允许有相同的 key,但允许有相同的 value(Object)
(5)字典是无序的
1、不可变词典 NSDictionary
字典初始化:
(1)以一个元素初始化
NSDictionary *dic = [NSDictionary dictionaryWithObject:numObj forKey:@"key"];
(2)初始化两个元素
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:
numObj, @"valueKey", numObj2, @"value2",nil];
(3)初始化新字典,新字典包含 otherDic
NSDictionary *dic = [NSDictionary dictionaryWithDictionary:otherDic];
(4)以文件内容初始化字典
NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:path];
(5)也可创建多维字典
访问:
NSLog(@"%@", persons[1][@"qq"]);
上述代码含义:
先取出 1 位置对应的字典
再取出字典中 qq 这个 key 对应的数据
常用方法:
(1)获取字典数量
NSInteger count = [dic count];
(2)通过 key 获取对应的 value 对象
NSObject *valueObj = [dic objectForKey:@"key"];
(3)将字典的 key 转成枚举对象,用于遍历
NSEnumerator *enumerator = [dic keyEnumerator];
(4)获取所有键的集合
NSArray *keys = [dic allKeys];
(5)获取所有值的集合
NSArray *values = [dic allValues];
2、可变数组 NSMutableDictionary
(1)初始化一个空的可变字典
NSMutableDictionary *dic2 = [NSMutableDictionary
dictionaryWithObjectsAndKeys:@"v1",@"key1",@"v2",@"key2",nil];
NSDictionary *dic3 = [NSDictionary dictionaryWithObject:
@"v3" forKey:@"key3"];
(2)向字典 2 对象中添加整个字典对象 3
[dic2 addEntriesFromDictionary:dic3];
(3)向字典 2 对象中最佳一个新的 key3 和 value3
[dic2 setValue:@"value3" forKey:@"key3"];
(4)初始化一个空的可变字典
NSMutableDictionary *dic1 = [NSMutableDictionary dictionary];
(5)将空字典 1 对象内容设置与字典 2 对象相同
[dic1 setDictionary:dic2];
(6)将字典中 key1 对应的值删除
[dic1 [email protected]"key1"];
NSArray *array = [NSArray arrayWithObjects:@"key1", nil];
(7)根据指定的数组(key)移除字典 1 的内容
[dic2 removeObjectsForKeys:array];
(8)移除字典所有对象
[dic1 removeAllObjects];
3、遍历字典
(1)快速枚举 for (id key in dic){
id obj = [dic objectForKey:key];
NSLog(@"%@", obj); }
(2)一般枚举
NSArray *keys = [dic allKeys];
inr length = [keys count];
for (int i = 0; i < length;i++){
id key = [keys objectAtIndex:i]; id obj = [dic objectForKey:key]; NSLog(@"%@", obj);
}
(3)通过枚举类型枚举
NSEnumerator *enumerator = [dic keyEnumerator];
id key = [enumerator nextObject];
while (key) {
id obj = [dic objectForKey:key];
NSLog(@"%@", obj);
key = [enumerator nextObject];
}
以上是关于NSDictionary/NSMutableDictionary的主要内容,如果未能解决你的问题,请参考以下文章