I am trying to use a UISearchBar
to query multiple properties of a NSManagedObject
I have a NSManagedObject
called Person
Fraser Hess over at CISMGF.com has a great search example. You can read the post at http://www.cimgf.com/2008/11/25/adding-itunes-style-search-to-your-core-data-application/
My code based off the post is:
NSArray *searchTerms = [searchText componentsSeparatedByString:@" "];
if ([searchTerms count] == 1) { // Search in name and description
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(name contains[cd] %@) OR (desc contains[cd] %@)", searchText, searchText];
[self.searchFetchedResultsController.fetchRequest setPredicate:predicate];
} else { // Search in name and description for multiple words
NSMutableArray *subPredicates = [[NSMutableArray alloc] init];
for (NSString *term in searchTerms) {
NSPredicate *pred = [NSPredicate predicateWithFormat:@"(name contains[cd] %@) OR (desc contains[cd] %@)", term, term];
[subPredicates addObject:pred];
}
NSPredicate *predicate = [NSCompoundPredicate andPredicateWithSubpredicates:subPredicates];
[self.searchFetchedResultsController.fetchRequest setPredicate:predicate];
}