ObjectiveC(4)_NSDictionary和NSMutableDictionary
程序员文章站
2024-01-15 19:41:58
...
NSDictionary
定义
Foundation
中的字典(NSDictionary,NSMutableDictionary
)是由键-值对组成的数据集合。正如在字典中查找单词的定义一样,通过key
找到value
。类似于java
中的map。主要特性有:
- key通常是字符串对象,也可以是其他任意类型对象。
- key的值必须是唯一的
- 键和值不可以为空nil,如果需要在一个字典对象中表示一个空值,可以使用NSNull对象。
NSDictionary
初始化
- 创建一个键值的dictionary
NSNumber *numValue = [NSNumber numberWithInt:10];
NSDictionary *dic1 = [NSDictionary dictionaryWithObject:numValue forKey:@"one"];
NSLog(@"创建一个键值的dictionary:%@",dic1);
- 创建多个键值的dictionary
NSDictionary *dic2 = [NSDictionary dictionaryWithObjectsAndKeys:numValue,@"one",numValue,@"two", nil];
NSLog(@"创建多个键值的dictionary:%@",dic2);
- 以其他字典来初始化新字典
NSDictionary *dic3 = [NSDictionary dictionaryWithDictionary:dic2];
NSLog(@"以其他字典来初始化新字典:%@",dic3);
NSDictionary
常用方法
- 获取dictionary数量
NSInteger count = [dic3 count];
NSLog(@"字典长度是:%ld",count);
- 通过key来或取value
NSString *value = [dic3 objectForKey:@"one"];
NSLog(@"通过key来或者value:%@",value);
- 将dictionary转换成枚举类型,用于遍历
NSEnumerator *enumDIc = [dic3 keyEnumerator];
- 获取所有的key
NSArray *keys = [dic3 allKeys];
NSLog(@"获取所有的key:%@",keys);
- 获取所有的value
NSArray *values = [dic3 allValues];
NSLog(@"获取所有的value:%@",values);
NSMutableDictionary
常用方法
- 创建可变字典
NSMutableDictionary *dic4 = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"v1",@"k1",@"v2",@"k2",@"v3",@"k3",@"v4",@"k4", nil];
NSLog(@"创建可变字典:%@",dic4);
- 初始化一个空的可变字典
NSMutableDictionary *dic5 = [NSMutableDictionary dictionary];
- 添加值
[dic5 setValue:@"v5" forKey:@"k5"];
NSLog(@"添加值:%@",dic5);
- 添加一个dictionary
[dic4 addEntriesFromDictionary:dic3];
NSLog(@"添加一个dictionary:%@",dic4);
- 给空dictionary设置另一个dictionary,会把之前的内容覆盖掉
[dic5 setDictionary:dic4];
NSLog(@"给空dictionary设置另一个dictionary:%@",dic5);
- 删除key对应的value
[dic5 removeObjectForKey:@"one"];
NSLog(@"删除key对应的value:%@",dic5);
-根据指定的keys数组删除dictionary
NSArray *removeKeys = [NSArray arrayWithObjects:@"k1",@"k2", nil];
[dic5 removeObjectsForKeys:removeKeys];
NSLog(@"根据指定的keys数组删除dictionary:%@",dic5);
- 删除所有的值
[dic5 removeAllObjects];
NSLog(@"删除所有的值:%ld",[dic5 count]);
Dictionary
遍历
- 快速枚举
for (id key in dic5) {
NSString *value = [dic5 objectForKey:key];
NSLog(@"快速枚举遍历:%@",value);
}
- for循环遍历
NSArray *values1 = [dic5 allValues];
NSArray *keys1 = [dic5 allKeys];
for (int i = 0; i < [dic5 count]; i++) {
// 能拿到索引
id key = [keys1 objectAtIndex:i];// 获取数组中的每一个key
id value = [dic5 objectForKey:key];
NSLog(@"获取value:%@",value);
// 不拿到索引
id value2 = [values1 objectAtIndex:i];
NSLog(@"%@",value2);
}
- 通过枚举类型枚举
NSEnumerator *enumDIc = [dic3 keyEnumerator];
id key = [enumDIc nextObject];
while ([key count] > 0) {
id value = [dic5 objectForKey:key];
NSLog(@"枚举类型遍历:%@",value);
key = [enumDIc nextObject];
}
// 另一种写法
id key;
while (key = [enumDIc nextObject]) {
id value = [dic5 objectForKey:key];
NSLog(@"枚举类型遍历:%@",value);
}
下一篇: 自媒体平台“北京时间”360欲将全身而退