Using NSPredicate with Core Data NSFetchedResultsController

南笙酒味 提交于 2019-11-29 23:53:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!