我有一个NSMutableDictionary,它包含一个项目数组(NSDictionary类型)。我需要删除存储在每个项目中的一个特定键(及其关联的对象)。什么是最好的方法呢?
示例结构:
NSDictionary *dict = @{
@"v" : @[
@{ @"key1": @"abc", @"key2" : @"def" },
@{ @"key1": @"ghi", @"key2" : @"jkl" }, ...
]
};
我想从嵌套字典元素中删除所有key1:
@{
@"v" : @[
@{ @"key2" : @"def" },
@{ @"key2" : @"jkl" }, ...
]
}
答案 0 :(得分:2)
这应该这样做:
NSMutableDictionary *dict = [@{
@"v" : @[
@{ @"key1": @"abc", @"key2" : @"def" },
@{ @"key1": @"ghi", @"key2" : @"jkl" }
]
} mutableCopy];
NSArray *oldArray = [dict objectForKey:@"v"];
NSMutableArray *newArray = [NSMutableArray array];
[oldArray enumerateObjectsUsingBlock:^(NSDictionary *dictionary, NSUInteger idx, BOOL *stop) {
NSMutableDictionary *mutableDictionary = [dictionary mutableCopy];
[mutableDictionary removeObjectForKey:@"key1"];
[newArray addObject:mutableDictionary];
}];
[dict setObject:newArray forKey:@"v"];
答案 1 :(得分:0)
对于您的主词典,您可以使用enumerateKeysAndObjectsUsingBlock:
枚举对象,对于可以使用的数组enumerateObjectsUsingBlock
[self.myDictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSArray *array = (NSArray *)obj;
[arr enumerateObjectsUsingBlock:^(id obj2, NSUInteger idx, BOOL *stop)
{
NSDictionary *dict = (NSDictonary *)obj2;
// remove item from dict
}];
}];
我没有测试它,但它应该给你一个想法。
答案 2 :(得分:-1)
枚举NSArray
并为每个词典调用[dict removeObjectForKey:@"key1"]
。
修改强> 如果它们是NSDictionary而不是NSMutableDictionary,请执行以下操作:
NSMutableDictionary *mutableDict = [[NSMutableDictionary alloc] init];
[mutableDict setDictionary:originalDict];
[mutableDict removeObjectForKey:@"key1"];
NSDictionary *newDict = [[NSDictionary alloc] initWithDictionary:mutableDict];
然后使用newDict
,可能会替换NSArray中的原始
使用整个解决方案再次进行修改:
NSArray *a = [outerDict objectForKey:@"v"];
NSMutableArray *newArray = [[NSMutableArray alloc] init];
for (NSDictionary d in a) {
NSMutableDictionary *mutableDict = [[NSMutableDictionary alloc] init];
[mutableDict setDictionary:d];
[mutableDict removeObjectForKey:@"key1"];
NSDictionary *newDict = [[NSDictionary alloc] initWithDictionary:mutableDict];
[newArray addObject:newDict];
}
[outerDict setObject:newArray ForKey:@"v"];
答案 3 :(得分:-1)
假设内部词典实际上是可变的(如你所说)并且不是内联词,你需要这样的东西:
NSString *removeKey = @"key1";
for (NSArray *array in [outerDict allValues])
{
for (NSMutableDictionary *dict in arrayOfDicts)
{
[dict removeObjectForKey:removeKey];
}
}
...但你仍然需要内部词典可变。如果你想将它设置为内联,并让它们变得可变,那么这将起作用:
NSDictionary *dict = @{
@"v" : @[
[@{ @"key1": @"abc", @"key2" : @"def" } mutableCopy],
[@{ @"key1": @"ghi", @"key2" : @"jkl" } mutableCopy]
]
};