简体   繁体   中英

filter NSArray with NSDictionary by int value

I have the following NSArray:

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

And I need to filter the array for establecimiento < 10 .

I'm trying this:

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

where self.establecimientoFiltro is an int with value: 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.

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

You should use blocks with Predicate to achieve this.

Let's assume your array is in myArray . Now make a predicate with range of your choice. As of now, you want it to be less than 10 for establecimientoFiltro .

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 .

Hope that is the efficient most & helpful to you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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