NSPredicates, scopes and SearchDisplayController
Posted
by Bryan Veloso
on Stack Overflow
See other posts from Stack Overflow
or by Bryan Veloso
Published on 2010-04-08T06:54:48Z
Indexed on
2010/04/10
23:13 UTC
Read the original article
Hit count: 725
Building a search with some custom objects and three scopes: All, Active, and Former. Got it working with the below code:
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString *)scope {
[[self filteredArtists] removeAllObjects];
for (HPArtist *artist in [self artistList]) {
if ([scope isEqualToString:@"All"] || [[artist status] isEqualToString:scope]) {
NSComparisonResult result = [[artist displayName] compare:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchText length])];
if (result == NSOrderedSame) {
[[self filteredArtists] addObject:artist];
}
}
}
}
This works fine and takes scope
into account. Since I wanted to search four fields at at time, this question helped me come up with the below code:
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString *)scope {
[[self filteredArtists] removeAllObjects];
NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"familyName CONTAINS[cd] %@ OR familyKanji CONTAINS[cd] %@ OR givenName CONTAINS[cd] %@ OR givenKanji CONTAINS[cd] %@", searchText, searchText, searchText, searchText];
[[self filteredArtists] addObjectsFromArray:[[self artistList] filteredArrayUsingPredicate:resultPredicate]];
}
However it no longer takes scope into account.
I have been playing around with if
statements, adding AND scope == 'Active'
, etc. to the end of the statement and using NSCompoundPredicates
to no avail. Whenever I activate a scope, I'm not getting any matches for it.
Just a note that I've seen approaches like this one that take scope into account, however they only search inside one property.
© Stack Overflow or respective owner