Core Data: Reset to the initial state

Deadly 提交于 2019-12-02 19:31:36

Wrap your changes in a NSUndoManager beginUndoGrouping and then a NSUndoManager endUndoGrouping followed by a NSUndoManager undo.

That is the correct way to roll back changes. The NSManagedObjectContext has its own internal NSUndoManager that you can access.

Update showing example

Because the NSUndoManager is nil by default on Cocoa Touch, you have to create one and set it into the NSManagedObjectContext first.

//Do this once per MOC
NSManagedObjectContext *moc = [self managedObjectContext];
NSUndoManager *undoManager = [[NSUndoManager alloc] init];
[moc setUndoManager:undoManager];
[undoManager release], undoManager = nil;

//Example of a grouped undo
undoManager = [moc undoManager];
NSManagedObject *test = [NSEntityDescription insertNewObjectForEntityForName:@"Parent" inManagedObjectContext:moc];
[undoManager beginUndoGrouping];
[test setValue:@"Test" forKey:@"name"];
NSLog(@"%s Name after set: %@", __PRETTY_FUNCTION__, [test valueForKey:@"name"]);
[undoManager endUndoGrouping];
[undoManager undo];
NSLog(@"%s Name after undo: %@", __PRETTY_FUNCTION__, [test valueForKey:@"name"]);

Also make sure that your accessors are following the rules of KVO and posting -willChange:, -didChange:, -willAccess: and -DidAccess: notifications. If you are just using @dynamic accessors then you will be fine.

As per Apple's documentation

Using

- (void)rollback; 
[managedObjectContext rollback];

Removes everything from the undo stack, discards all insertions and deletions, and restores updated objects to their last committed values.

Here

Try [managedObjectContext refreshObject:ingredient mergeChanges:NO] prior to the second NSLog call.

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