Core Data: Reset to the initial state

2019-03-10 01:27发布

I have an object, I make some changes to it, but I don't want to save them, I want the 'old' values.

I've tried with:

[managedObjectContext rollback];
[managedObjectContext redo];
[managedObjectContext reset];

and none of them seems to work ...

NSLog(@"current: %@",ingredient.name); // ===> bread
[ingredient setName:@"test new data"];
NSLog(@"new: %@",ingredient.name); // ===> test new data

[managedObjectContext rollback];
[managedObjectContext redo];
[managedObjectContext reset];

NSLog(@"current: %@",ingredient.name); // ===> test new data

// I want again ===> bread

Should I refetch the object again ?

thanks,

r.

3条回答
叛逆
2楼-- · 2019-03-10 02:00

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.

查看更多
混吃等死
3楼-- · 2019-03-10 02:01

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

查看更多
劫难
4楼-- · 2019-03-10 02:07

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

查看更多
登录 后发表回答