【问题标题】:filter NSArray with NSDictionary by int value使用 NSDictionary 按 int 值过滤 NSArray
【发布时间】:2014-01-09 00:32:41
【问题描述】:

我有以下 NSArray:

(
        {
        establecimiento = 15;
        internet = 500;
    },
        {
        establecimiento = 0;
        internet = 1024;
    },
        {
        establecimiento = 24;
        internet = 300;
    }
)

我需要为establecimiento < 10 过滤数组。

我正在尝试这个:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"establecimiento = %@", [NSNumber numberWithInt:self.establecimientoFiltro]];

self.establecimientoFiltro 是一个 int 值:10

但是我有一个空数组。

希望能清楚我的问题,并提前感谢您的回答。

问候, 维克多

【问题讨论】:

  • 如果你想要
  • @user3175572 在下面查看我的答案以获得灵活的输出。
  • 而且不需要把你的号码转换成NSNumber——你可以直接用%d这个号码。
  • 看看下面的答案,如果这让您感到困惑,请告诉我。好的
  • 您只需要在谓词格式中定义适当的条件

标签: ios objective-c nsarray nsdictionary nspredicate


【解决方案1】:

您的谓词检查该值是否等于十,而不是小于十。您收到一个空数组,因为您提供给我们的数组不包含 establecimiento 键返回值 10 的字典。

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"establecimiento < 10"];

【讨论】:

    【解决方案2】:

    您应该使用blocksPredicate 来实现这一点。

    假设您的数组位于myArray。现在用您选择的范围创建一个谓词。截至目前,您希望 establecimientoFiltro 的值小于 10。

    NSPredicate *keyPred = [NSPredicate predicateWithBlock:^BOOL(id  obj, NSDictionary *bindings) {
        NSRange myRange = NSMakeRange (0, 9);
        NSInteger rangeKey = [[obj valueForKey:@"establecimientoFiltro"]integerValue];
        if (NSLocationInRange(rangeKey, myRange)) {
            // found
            return YES;
        } else {
            // not found
            return NO;
        }
    }];
    
    NSArray *filterArray = [myArray filteredArrayUsingPredicate:keyPred];
    NSLog(@"%@", filterArray);
    

    您会在filteredArray 中过滤您的结果。

    希望这是最有效且对您有帮助的。

    【讨论】:

      猜你喜欢
      • 2012-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-17
      • 2010-10-31
      • 1970-01-01
      • 2013-11-20
      相关资源
      最近更新 更多