我有以下数组,但是,有一种方法可以在以下初始化后为key
中的每个字典项添加新的value
和NSMutableArray
(例如年龄) 。
NSMutableArray* names = [NSMutableArray arrayWithObjects:
[NSDictionary dictionaryWithObjectsAndKeys:
@"Joe",@"firstname",
@"Bloggs",@"surname",
nil],
[NSDictionary dictionaryWithObjectsAndKeys:
@"Simon",@"firstname",
@"Templar",@"surname",
nil],
[NSDictionary dictionaryWithObjectsAndKeys:
@"Amelia",@"firstname",
@"Pond",@"surname",
nil],
nil];
答案 0 :(得分:3)
您可以使用dip链接执行此操作。
以下是示例代码:
NSMutableDictionary mutableCopy = (NSMutableDictionary )CFPropertyListCreateDeepCopy(kCFAllocatorDefault, (CFDictionaryRef)originalDictionary, kCFPropertyListMutableContainers);
答案 1 :(得分:1)
如果您可以将字典数组定义为可变字典,那么您可以按照以下方式执行所需的操作:
NSMutableArray* names = [NSMutableArray arrayWithObjects:
[NSMutableDictionary dictionaryWithObjectsAndKeys:
@"Joe",@"firstname",
@"Bloggs",@"surname",
nil],
[NSMutableDictionary dictionaryWithObjectsAndKeys:
@"Simon",@"firstname",
@"Templar",@"surname",
nil],
[NSMutableDictionary dictionaryWithObjectsAndKeys:
@"Amelia",@"firstname",
@"Pond",@"surname",
nil],
nil];
for (NSMutableDictionary *dic in names) {
dic[@"age"] = @21;
}
请注意,初始数组中的每个元素现在都是NSMutableDictionary
intsances而不是NSDictioanry
。如果由于某种原因你不能这样做,那么你需要从数组中获取每个字典,将其转换为可变实例,然后用新的字典实例替换相关的数组元素。
如果您无法为数组创建NSMutableDictionary
个实例,那么您需要的代码将如下所示:
NSMutableArray* names = [NSMutableArray arrayWithObjects:
[NSDictionary dictionaryWithObjectsAndKeys:
@"Joe",@"firstname",
@"Bloggs",@"surname",
nil],
[NSDictionary dictionaryWithObjectsAndKeys:
@"Simon",@"firstname",
@"Templar",@"surname",
nil],
[NSDictionary dictionaryWithObjectsAndKeys:
@"Amelia",@"firstname",
@"Pond",@"surname",
nil],
nil];
[names enumerateObjectsUsingBlock:^(NSDictionary *dic, NSUInteger idx, BOOL * _Nonnull stop) {
NSMutableDictionary *dic2 = [dic mutableCopy];
dic2[@"age"] = @21;
names[idx] = dic2;
}];
答案 2 :(得分:1)
如果要在Dictionary中添加键和值,请使用NSMutableDictionary并在字典中添加键和值。
以下是代码:
NSMutableArray* names = [NSMutableArray arrayWithObjects:
[NSDictionary dictionaryWithObjectsAndKeys:
@"Joe",@"firstname",
@"Bloggs",@"surname",
nil],
[NSDictionary dictionaryWithObjectsAndKeys:
@"Simon",@"firstname",
@"Templar",@"surname",
nil],
[NSDictionary dictionaryWithObjectsAndKeys:
@"Amelia",@"firstname",
@"Pond",@"surname",
nil],
nil];
for (int i=0; i<names.count; i++) {
NSMutableDictionary *name = [NSMutableDictionary dictionaryWithDictionary:names[i]];
NSDictionary *test = [NSDictionary dictionaryWithObject:@"Test" forKey:@"Demo"];
[name addEntriesFromDictionary:test];
names[i] = name;
}
NSLog(@"%@",names);