iOS CoreData NSPredicate to query multiple properties at once

后端 未结 8 1821
刺人心
刺人心 2020-12-23 22:39

I am trying to use a UISearchBar to query multiple properties of a NSManagedObject I have a NSManagedObject called Person

8条回答
  •  [愿得一人]
    2020-12-23 22:57

    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];
    }
    

提交回复
热议问题