问题
I have a fetchedResultsController that has returned all records for my entity "Account".
I would like to quickly search all Account records for the attribute "lastName" == value, and give me back the Account object, or at least the indexPath of the object in the fetchedResultsController. There should only be 1 object returned.
Other than iterate through every objectAtIndexPath, is there a better way to search the fetchController using NSPredicate?
回答1:
mootymoots, just filter the fetched objects with another predicate...
NSPredicate *lastNameMatch = ...
NSArray *matchingFetchedObjects = [fetchedResultsController.fetchedObjects filteredArrayUsingPredicate:lastNameMatch];
That leaves your fetchedResultsController
results un-altered, but gives you an array with a match for the last name predicate.
回答2:
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// set up fetch request
...
NSPredicate *requestPredicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"(lastName like '%@')", self.lastName]];
[fetchRequest setPredicate:requestPredicate];
...
// perform fetch
NSError *error = nil;
if (![self.fetchedResultsController performFetch:&error]) {
// handle error...
}
...
Account *uniqueAccount = [[self.fetchedResultsController fetchedObjects] anyObject]; // assuming lastName attribute is unique
来源:https://stackoverflow.com/questions/2082206/using-nspredicate-with-core-data-nsfetchedresultscontroller