我需要为Core Data
对象实现取消/保存行为。我有一个UITableView
,我从NSFetchedResultsController
获得了数据。
- (void) configureWithCategoryItem: (CategoryItem *) categoryItem
{
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:[CategoryItem entityName]];
request.predicate = [NSPredicate predicateWithFormat:@"categoryId = %@", categoryItem.categoryId];
request.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"title" ascending:YES]];
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request
managedObjectContext:[CategoryItem defaultContext]
sectionNameKeyPath:@"title"
cacheName:nil];
[self.fetchedResultsController performFetch: NULL];
self.layers = [self categoryLayers];
self.sectionTitle = categoryItem.title;
}
每次点击此表视图中的单元格
LayerItem *layerItem = [self.layers objectAtIndex:indexPath.row];
layerItem.isSelected = [NSNumber numberWithBool:YES];
在导航栏中我有两个按钮: 取消 - 我需要关闭控制器而不将结果保存到核心数据, 保存 - 我需要保存结果并关闭控制器
现在,save方法如下所示:
- (void) saveChanges
{
NSManagedObjectContext *localContext = self.fetchedResultsController.managedObjectContext;
if ([localContext hasChanges]) {
[localContext save: NULL];
[[NSNotificationCenter defaultCenter] postNotificationName:kEADatabaseWasUpdated object:nil];
}
}
Core Data
中是否有某些工具可以帮助我实现这种行为?
我尝试使用单独的NSManagedObjectContext
和mergeChangesFromContextDidSaveNotification
但未获得好结果。等待您的帮助。
答案 0 :(得分:0)
- (void) cancelChanges
{
NSManagedObjectContext *localContext = self.fetchedResultsController.managedObjectContext;
[localContext rollback];
}