简体   繁体   English

通过int值过滤具有NSDictionary的NSArray

[英]filter NSArray with NSDictionary by int value

I have the following NSArray: 我有以下NSArray:

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

And I need to filter the array for establecimiento < 10 . 我需要过滤establecimiento < 10的数组。

I'm trying this: 我正在尝试:

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

where self.establecimientoFiltro is an int with value: 10 其中self.establecimientoFiltro是一个整数,其值是:10

But I have as result an empty array. 但结果我有一个空数组。

Hope to be clear with my question and thank you in advance for your answers. 希望清楚我的问题,并预先感谢您的回答。

Regards, Victor 问候,维克多

Your predicate checks to see if the value is equal to ten, not less than ten. 您的谓词检查以查看该值是否等于十,不小于十。 You receive an empty array because that you provided us with does not contain a dictionary where the establecimiento key returns a value of 10. 您收到一个空数组,因为您提供给我们的数组不包含establecimiento键返回值10的字典。

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

You should use blocks with Predicate to achieve this. 您应该将blocksPredicate结合使用以实现此目的。

Let's assume your array is in myArray . 假设您的数组在myArray Now make a predicate with range of your choice. 现在根据您的选择范围做出谓词。 As of now, you want it to be less than 10 for establecimientoFiltro . 截至目前,您希望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);

You get your result filtered in the filteredArray . 您将结果过滤在filteredArray

Hope that is the efficient most & helpful to you. 希望这对您最有效和最有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM