Filtering NSArray of NSDictionary objects using NSPredicate

前端 未结 2 1755
情话喂你
情话喂你 2020-12-23 23:37

I have an NSArray of NSDictionary objects. I want to filter the array based on keys of the dictionaries using NSPredicate. I have been doing something like this:



        
相关标签:
2条回答
  • 2020-12-24 00:10

    When using a dynamic key, you should use the %K token instead of %@. You also don't want the quotes around the value token. They will cause your predicate to test for equality against the literal string @"%@" instead of against value.

    NSString *predicateString = [NSString stringWithFormat:@"%K == %@", key, value];
    

    This is documented in the Predicate Format String Syntax guide.


    Edit: As Anum Amin points out, +[NSString stringWithFormat:] doesn't handle predicate formats. You want [NSPredicate predicateWithFormat:@"%K == %@", key, value] instead.

    0 讨论(0)
  • 2020-12-24 00:14

    For me, Kevin's answer did not work. I used:

    NSPredicate *predicateString = [NSPredicate predicateWithFormat:@"%K contains[cd] %@", keySelected, text];//keySelected is NSString itself
            NSLog(@"predicate %@",predicateString);
            filteredArray = [NSMutableArray arrayWithArray:[YourArrayNeedToFilter filteredArrayUsingPredicate:predicateString]];
    
    0 讨论(0)
提交回复
热议问题