简体   繁体   中英

NSPredicate and filtering

I have a NSMutableArray called comboData which I am trying to filter out:

  NSMutableArray * filteredVersion = [[NSMutableArray alloc] init];
  NSPredicate    *predicate        = [NSPredicate predicateWithFormat:@"id >= %d AND id <= %d",1,7];
  [filteredVersion setArray: [comboData filteredArrayUsingPredicate:
                          predicate]
                        ];

I get an unknown selector error message

  [__NSCFNumber length]: unrecognized selector sent to instance 0xa966350

at the second line. What I (anew) missing ?

[EDIT]

The comboData is as follow (printed out in the debug area)

combo data (
    {
    id = 1;
    label = "A";
    name = '';

},
    {
    id = 2;
    label = "B";
    name = '';

},

OK, so your array comboData is filled with NSDictionaries .

An NSDictionary can only contain objects.

It looks like the key id references a number and so it will be a NSNumber .

In your predicate you are treating it as an int.

You will need something like this...

// erm... not sure. Can you not just use a comparator?
// NSPredicate *predicate = [NSPredicate predicateWithFormat:@"id >= %d AND id <= %d",1,7];

NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(NSDictionary *dictionary, NSDictionary *bindings) {
    NSNumber *idNumber = dictionary[@"id"];

    return [idNumber intValue] >= 1 && [idNumber intValue] <= 7;
}];

This should work.

Just use this instead of your current predicate.

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