views:

144

answers:

2

I'd like to use NSUndoManager in an iPhone application on CoreData (NSManagedObject) objects such that I can save (and later restore) the state of the NSUndoManager if the application exits prematurely (say, due to a phone call coming in). I.e. as opposed to automatically discarding or saving the changes accumulated in the NSUndoManager, I would like to restore them so that the user has the option to explicitly discard or save them when they restart the app.

Has anyone had any experience with this? Can anyone recommend this (or an alternative) approach to managing pending changes in a NSManagedObjectContext when the application is interrupted?

+1  A: 

The NSUndoManager does not actually store state, it stores a stack of actions that will restore the state. For example, if you have an object XXX and it has a property name which is a string and you change that name from "Steve" to "Joe", what the NSUndoManager stores is a target, selector and object. The target would be the instance of XXX, the selector would be @selector(setName:) and the object would be @"Steve".

By storing that information, if the undo stack is popped it will call -setName: on the instance of object XXX with the value of @"Steve" and thus restoring its state. There is some additional work done around KVO, etc. but that is the basics.

At first I theorized that you could write out the NSManagedObjectID, the selector (using NSStringFromSelector) and the object to disk and restore them by calling -registerUndoWithTarget: selector: object:. However upon further review of the documentation, there is no way to access the stack to be able to iterate over it.

Marcus S. Zarra
D Carney
A: 

Note that one possible work-around exists by using separate NSManagedObjectContexts such that some are saved on shutdown whereas others have their changes rolled back. It's not perfect, but I found a suitable solution to my problem with this alternative.

D Carney