NSDictionary:字典,以key-value存储数据, 存储的内存不是连续的,使用键值编码。
1.NSDictionary的声明
NSArray *arr_key = [NSArray arrayWithObjects:@"1", @"2", @"3", nil];
NSArray *arr_value = [NSArray arrayWithObjects:@"a",@"b",@"c",nil];
NSDictionary *dic = [NSDictionary dictionaryWithObjects:arr_value forKeys:arr_key];
NSLog(@"dic = %@", dic);
// NSDictionary的简单声明方式
NSDictionary *dic_s = @ { @"1":@"a", @"2":@"b", @"3":@"c" };
NSLog(@"dic_s = %@", dic_s);
2. NSDictionary的大小
int count = (int) [dic count];
3.取得NSDictionary的值
NSString *value = [ dic valueForKey:@"1" ]; // 取出key对应的值
NSString *vaule)1 = [ dic objectForKey:@"1" ]; // 取出key对应的值
NSArray *array_key = [ dic allKeys ]; // 取出NSDictionary中所有的key值,组成数组
NSArray *array_value = [ dic allValues ]; // 取出NSDictionary中所有的value值,组成数组
// 匹配获得NSDictionary中部分key对应的value,如果找到对应的value,则返回value本身,若不存在,则返回notFoundMarker
NSArray *array = [dic objectsForKeys:[ NSArray arrayWithObjects:@"1", @"2", @"5",nil ] notFoundMarker:@"not found"];
4.NSDictionary遍历
for(NSString *key in dic)
{
NSString *val = [dic objectForKey:key];
NSLog(@"%@ = %@", key, val);
}
NSEnumerator *en = [dic keyEnumerator]; //枚举器遍历NSDictionary
id key = nil;
while (key = [en nextObject])
{
id val = [en nextObject];
NSLog(@"%@ = %@", key,val);
}
5.NSMutableDictionary可变字典
NSMutableDictionary *dic_m = [[ NSMutableDictionary alloc ] init ] ;
5-1 给NSMutableDictionary添加key-value的数值
[dic_m setObject:@"a" forKey:@"1"]; //添加了key=1,value=a的数值
[dic_m setObject:@"b" forKey:@"2"];
5-2 删除键值对
[ dic_m removeAllObjects ]; // 删除NSMutableDictionary中所有的k-v数值
[ dic_m removeObjectForKey:@"2" ]; // 删除NSMutableDictionary中key="1"的键值对
[ dic_m removeObjectsForKeys:[ NSArray arrayWithObjects:@"1", @"2", @"3", nil ] ] ; //删除多个key-value的键值对