假设生成正确提取(某种条件语句)的逻辑在您的 NSFetchedResultsController 实例的 getter 中。然后真的很容易
self.fetchedResultsController = nil; // this destroys the old one
[self.tableview reloadData];
// when the table view is reloaded the fetchedResultsController will be lazily recreated
编辑:添加我所做的事情的完整代码示例。基本上我有一个 NSDictionary entityDescription,它保存值来自定义 NSFetchedResultsController 的创建。如果我想更改 fetchRequest,我更改我的 entityDescription 变量以指示新值并覆盖设置器以重置 fetchedResultsController 并重新加载表。它给了你基本的想法。
- (NSFetchedResultsController *)fetchedResultsController
{
if (__fetchedResultsController != nil) {
return __fetchedResultsController;
}
if (self.entityDescription == nil) {
return nil;
}
// Set up the fetched results controller.
// Create the fetch request for the entity.
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:[self.entityDescription objectForKey:kEntityName]];
// Set the batch size to a suitable number.
[fetchRequest setFetchBatchSize:20];
// Edit the sort key as appropriate.
if ([[self.entityDescription objectForKey:kEntitySortField] isEqualToString:@"null"] == NO) {
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:[self.entityDescription objectForKey:kEntitySortField] ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
}
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:self.moc sectionNameKeyPath:nil cacheName:nil];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;
NSError *error = nil;
if (![self.fetchedResultsController performFetch:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return __fetchedResultsController;
}
- (void)setEntityDescription:(NSDictionary *)entityDescription
{
_entityDescription = entityDescription;
self.fetchedResultsController = nil;
[self.tableView reloadData];
}