ios - 根据键数组过滤NSDictionary

标签 ios objective-c nsarray nsdictionary

我有一个“列入白名单”的键数组,我想根据这些键过滤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/

相关文章:

iOS 因 Google 登录而被拒绝。最新的 Google SignIn (4.0.0) 去 safari

ios - NSArray 不按数字顺序排序

ios - 位图 CGContext 绘图不断增加内存使用量

ios - 如何在 SwiftUI 中水平对齐 View 与导航栏项目

iOS内存泄漏与 Nib

objective-c - 核心数据:跨关系计数

ios - Objective C Google Maps API 公钥函数

iphone - 在 iPad 上展示 iAd 和 AdMobAd

iphone - NSPredicate 子查询语法

ios - 即使我添加了多个对象,数组也只包含一项