开发者

NSPredicate array contains question [duplicate]

开发者 https://www.devze.com 2023-03-31 05:18 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Searching/Filtering a custom class array with a NSPredicate
This question already has answers here: Closed 11 years ago.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号