Help creating a predicate for use with filteredArrayUsingPredicate
I am trying to learn how to use predicates and so am trying to replace the following working code with filteredArrayUsingPredicate...
[filteredLocations removeAllObjects];
for (NSString *location in locations) {
NSRange range = [location rangeOfString:query options:NSCaseInsensitiveSearch];
if (range.length > 0) {
[filteredLocations addObject:location];
}
}
Instead I am trying....
开发者_运维百科[filteredLocations removeAllObjects];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains %@", searchText];
[filteredLocations addObjectsFromArray: [locations filteredArrayUsingPredicate:predicate]];
I am not getting the same results with the predicate as I am with for loop rangeOfString. With the range of string for example searchText returns an 8 item array while with the same value returns only 2 with the predicate. Another example, hono will find honolulu in the locations array while it will not find anything using the predicate.
As I understand it SELF represents the object object being evaluated ie. the locations array, so I think that is the correct syntax.
Any help would be appreciated
Thanks, John
I thought that in your for loop, you specify an option NSCaseInsensitiveSearch but in the predicate you didn't.
You can try with this one
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(SELF contains[cd] %@)", searchText];
More details can be looked at here NSPredicate Tutorial
精彩评论