下面是我为tableView实现的方法" reset"按钮。我已经验证了实体中的条目正在被删除,但是我的controllerWillChangeContent在删除后没有被调用。有没有办法手动调用此方法?
CoreDataStack *coreDataStack = [[CoreDataStack alloc]init];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"FoodEntry"];
[fetchRequest setIncludesPropertyValues:NO];
NSError *error;
NSArray *fetchedObjects = [coreDataStack.managedObjectContext executeFetchRequest:fetchRequest error:&error];
for (NSManagedObject *object in fetchedObjects)
{
[coreDataStack.managedObjectContext deleteObject:object];
}
error = nil;
[coreDataStack.managedObjectContext save:&error];
编辑:FRC代码
- (NSFetchedResultsController *)fetchedResultsController {
if (_fetchedResultsController != nil) {
return _fetchedResultsController;
}
CoreDataStack *coreDataStack = [CoreDataStack defaultStack];
NSFetchRequest *fetchRequest = [self entryListFetchRequest];
_fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:coreDataStack.managedObjectContext sectionNameKeyPath:nil cacheName:nil];
_fetchedResultsController.delegate = self;
return _fetchedResultsController;
}
答案 0 :(得分:0)
在不知道CoreDataStack
的内部结构的情况下无法确定,但看起来您使用的是两个不同的堆栈:请注意您的代码使用:
CoreDataStack *coreDataStack = [[CoreDataStack alloc] init];
而FRC使用:
CoreDataStack *coreDataStack = [CoreDataStack defaultStack];
您可以将代码更改为与FRC一样使用(defaultStack
可能是单例,并且只要调用它就会返回相同的堆栈)。但是如果FRC与删除代码属于同一类,那么使用FRC的managedObjectContext会更容易(也更清晰):
NSManagedObjectContext *context = self.fetchedResultsController.managedObjectContext
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"FoodEntry"];
[fetchRequest setIncludesPropertyValues:NO];
NSError *error;
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
for (NSManagedObject *object in fetchedObjects)
{
[context deleteObject:object];
}
error = nil;
[context save:&error];
顺便提一下,如果executeFetchRequest:
和save:
返回错误,总是值得检查。