NSPredicates, scopes, and SearchDisplayController

Building a search using some custom objects and three areas: All, Active, and Former. Worked with the code below:

- (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 into account scope . Since I wanted to search for four fields at a time, this question helped me come up with the code below:

 - (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 into account the scope.

I played with if , adding AND scope == 'Active' , etc. at the end of the instruction and using NSCompoundPredicates no avail. Whenever I activate an area, I don't get any matches.


Just notice that I have seen approaches like this that take into account scope, however they only look for one property.

+4
source share
1 answer

Here's how to do it:

 NSPredicate * template = [NSPredicate predicateWithFormat:@"familyName CONTAINS[cd] $SEARCH " @"OR familyKanji CONTAINS[cd] $SEARCH " @"OR givenName CONTAINS[cd] $SEARCH " @"OR givenKanji CONTAINS[cd] $SEARCH"]; - (void)filterContentForSearchText:(NSString *)search scope:(NSString *)scope { NSPredicate * actual = [template predicateWithSubstitutionVariables:[NSDictionary dictionaryWithObject:search forKey:@"SEARCH"]]; if ([scope isEqual:@"All"] == NO) { NSPredicate * scopePredicate = [NSPredicate predicateWithFormat:@"scope == %@", scope]; actual = [NSCompoundPredicate andPredicateWithSubpredicates:[NSArray arrayWithObjects:actual, scopePredicate, nil]]; } [[self filteredArtists] setArray:[[self artistList] filteredArrayUsingPredicate:actual]]; } 
+4
source

Source: https://habr.com/ru/post/1306333/


All Articles