iPhone Core Data/undo gotcha of the day

newcore_data_iosIn general, I like the NSUndoManager functionality in iOS, but sometimes the secret handshakes you need to know can really get me down. For example, I needed to disable undo/redo when setting a particular property of a model entity. Reading the documentation, this seemed pretty straightforward:

[[theApp.managedObjectContext undoManager] disableUndoRegistration];
        detailItem.fieldImageFile = relativePath;
        [[theApp.managedObjectContext undoManager] enableUndoRegistration];

Seemed very clear, but it didn’t work! So, after much poking around on the Internet, I found a posting that alluded to the fact that changes to undo don’t occur until the run loop executes. So, to get the desired effect, I ended up with the following code:

[[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode beforeDate:[NSDate date]];
        [[theApp.managedObjectContext undoManager] disableUndoRegistration];
        detailItem.fieldImageFile = relativePath;
        [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode beforeDate:[NSDate date]];
        [[theApp.managedObjectContext undoManager] enableUndoRegistration];

Yet another head-scratching API decision from Apple.

Leave a Reply

Your email address will not be published. Required fields are marked *