NSPredicate array contains question [duplicate]
Possible Duplicate:
Searching/Filtering a custom class array with a NSPredicate
I have a array that contains objects of a custom class, and I would like to filter the array based on if one of the classes attributes contains a custom string. I have a method that is passed the attribute that I want to be searched (column) and the string that it will search for (searchString). H开发者_开发百科ere is the code I have:
NSPredicate *query = [NSPredicate predicateWithFormat:@"%@ contains %@", column, searchString];
NSMutableArray *temp = [displayProviders mutableCopy];
[displayProviders release];
displayProviders = [[temp filteredArrayUsingPredicate:query] mutableCopy];
[temp release];
For some reason, this always returns an empty array. Three of the four columns are ints or doubles, so I could add an if statment to convert searchString to a number, if needed. However, even when searching the attribute that is a string, and should have some rows that contain the string searchString, an empty array is returned.
Am I using "contains" incorrectly?
For searching strings in a predicate, i've found that wrapping single quotation marks around what I am searching for works best and using contains[cd]
rather than contains
like below (the [cd] bit specifies a case & diacritic insensitive search):
NSPredicate *query = [NSPredicate predicateWithFormat:@"%@ contains[cd] '%@'", column, searchString];
For searching a column with Integers, using double equals should work fine too:
NSPredicate *query = [NSPredicate predicateWithFormat:@"%@ == %@", column, searchString];
I think your predicate should be [NSPredicate predicateWithFormat: @"column contains %@", searchString]
The way it is right now, your predicate becomes ""column" contains "string""
, which always evaluates to false.
Using contains[cd]
may also be a good idea depending on your situation.
精彩评论