Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undo Management with Core Data

I'm trying to implement undo support using Core Data on the iPhone and I ran into a few problems.

I currently have a couple of managed objects set up but when I make changes to their properties, these changes don't get recorded by the undo manager. From my understanding, Core Data is supposed to have this automatically set up and I should be able to have basic undo and redo support for changes, creation and deletion of managed objects.

Is there special way of making changes to the objects so that they get recorded by the undo manager? Or should I be registering undo actions for each change?

Also, suppose the application slides into a detailed view for editing a specific object. I would like to be able to undo all changes made when say, the cancel button is hit. Would undo grouping be applicable here? What is the difference between committing a group and have another undo manager manage the finer actions in the detailed view versus using just having one undo manager (the one included with the managed object context)?

Thanks!

like image 386
Matthew Avatar asked Aug 07 '09 16:08

Matthew


1 Answers

While the undo features will work pretty much out of the box, you do need to allocate an NSUndoManager for the NSManagedObjectContext for which you want undo support.

The easiest way to do this is to set up the undo support when something asks your appDelegate for the NSManagedObjectContext

This is the default method that apple gives you:

- (NSManagedObjectContext *) managedObjectContext {

    if (managedObjectContext != nil) {
        return managedObjectContext;
    }

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {
        managedObjectContext = [[NSManagedObjectContext alloc] init];

        [managedObjectContext setPersistentStoreCoordinator: coordinator];
    }
    return managedObjectContext;
}

Modify it to look like this:

- (NSManagedObjectContext *) managedObjectContext {

    if (managedObjectContext != nil) {
        return managedObjectContext;
    }

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {
        managedObjectContext = [[NSManagedObjectContext alloc] init];

        //Undo Support
        NSUndoManager *anUndoManager = [[NSUndoManager  alloc] init];
        [managedObjectContext setUndoManager:anUndoManager];
        [anUndoManager release];

        [managedObjectContext setPersistentStoreCoordinator: coordinator];
    }
    return managedObjectContext;
}
like image 53
user160917 Avatar answered Oct 18 '22 02:10

user160917