开发者

Core Data: Reset to the initial state

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开发者_JAVA百科"];
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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜