Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"];
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.

like image 950
mongeta Avatar asked Feb 06 '10 19:02

mongeta


2 Answers

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.

like image 156
Marcus S. Zarra Avatar answered Sep 21 '22 13:09

Marcus S. Zarra


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

like image 44
Raj Avatar answered Sep 21 '22 13:09

Raj