使用一些自定义对象和三个范围构建搜索:All、Active和Former。让它使用以下代码:
- (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];
}
}
}
}
这工作正常并考虑scope
在内。由于我想一次搜索四个字段,所以这个问题帮助我想出了以下代码:
- (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]];
}
但是,它不再考虑范围。
我一直在玩弄if
语句,在语句的末尾添加AND scope == 'Active'
等,NSCompoundPredicates
但无济于事。每当我激活一个范围时,我都没有得到任何匹配项。
请注意,我已经看到像这种考虑范围的方法,但是它们只在一个属性内搜索。