我有一个“列入白名单”的键数组,我想根据这些键过滤NSDictionary。
NSArray *whiteList = @["one", "two"];
NSDictionary *dictionary = @{
@"one" : @"yes",
@"two" : @"yes",
@"three" : @"no"
};
NSDictionary *whiteDictionary = [dictionary dictionaryWithValuesForKeys:whiteList];
产生:
{
one = "yes";
two = "yes;
}
但是,如果我的字典不包含一个或多个键:
NSArray *whiteList = @["one", "two"];
NSDictionary *dictionary = @{
@"one" : @"yes"
};
NSDictionary *whiteDictionary = [dictionary dictionaryWithValuesForKeys:whiteList];
我回来了:
{
one = "yes";
two = "<null>";
}
有没有一种方法可以根据一组键过滤字典,而不会得到不存在的键。
最佳答案
更新
您可以通过过滤原始字典的所有键,然后从过滤后的键列表构建列入白名单的字典来获得功能解决方案:
NSDictionary *whiteDictionary = [dictionary dictionaryWithValuesForKeys:[dictionary.allKeys filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self IN %@", whiteList]]];,
或在两行中,通过为谓词声明一个单独的变量,以减小行的大小:
NSPredicate *whitelistPredicate = [NSPredicate predicateWithFormat:@"self IN %@", whiteList];
NSDictionary *whiteDictionary = [dictionary dictionaryWithValuesForKeys:[dictionary.allKeys filteredArrayUsingPredicate:whitelistPredicate]];,
原始答案
半功能方法如下所示:
NSDictionary *whiteDictionary = [dictionary dictionaryWithValuesForKeys:whiteList];
whiteDictionary = [whiteDictionary dictionaryWithValuesForKeys:[whiteDictionary keysOfEntriesPassingTest:^(NSString *key, id obj, BOOL *stop) { return obj != [NSNull null]; }]];
另外,您可以枚举字典并构建过滤后的字典:
NSMutableDictionary *whiteDictionary = [NSMutableDictionary dictionary];
[dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *key, id obj, BOOL *stop) {
if ([whiteList containsObject:key]) {
whiteDictionary[key] = obj;
}
}
关于ios - 根据键数组过滤NSDictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35003710/