【问题标题】:Get a list of Keys from NSDictionary containing NSNumber bools where the value is @YES从 NSDictionary 获取包含 NSNumber 布尔值的键列表,其中值为 @YES
【发布时间】:2012-11-02 13:54:01
【问题描述】:

我正在尝试获取一个键数组,其中 NSDictionary 中对应键的值为 @YES

对于 EG,: 起始字典:

NSDictionary* dict = @{@"key1" : @YES, @"key2": @YES, @"key3": @NO, @"key4": @NO};

期望的结果:

NSArray* array = @[@"key1", @"key2"];

我尝试使用 NSPredicates 和 subpredicates 执行此操作,但找不到符合我要求的。我的“工作”但丑陋的解决方案是:

NSMutableArray* array = [[NSMutableArray alloc] initWithCapacity:0];
NSDictionary* dict = @{@"key1" : @YES, @"key2": @YES, @"key3": @NO, @"key4": @NO};
for (NSString* key in [dict allKeys]) {
    if ([[dict objectForKey:key] isEqualToNumber:@YES])
        [array addObject:key];
}

有什么更好的方法可以做到这一点,可能是NSPredicates?。

【问题讨论】:

    标签: objective-c ios6 nsarray nsdictionary nspredicate


    【解决方案1】:

    这种方法可以消除很多混乱

    NSArray *results = [dict keysOfEntriesPassingTest:^(id key, id obj, BOOL *stop) {
      return [obj isEqualToNumber:@YES];
    }].allObjects;
    
    NSLog(@"%@", results);
    

    【讨论】:

    • 谢谢!这正是我知道我可以做但不知道如何做的事情。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-15
    • 2015-04-01
    • 1970-01-01
    • 2015-08-30
    • 2022-01-05
    • 2020-09-10
    相关资源
    最近更新 更多