An alternative way to disable undo registration when using Core Data

As previously discussed, Core Data takes a little coaxing if you want to disable undo registration. The standard approach is:

[[self managedObjectContext] processPendingChanges];
[[[self managedObjectContext] undoManager] disableUndoRegistration];
// Make your special changes to the managed object
[[self managedObjectContext] processPendingChanges];
[[[self managedObjectContext] undoManager] enableUndoRegistration];

The main point is to force through any changes the context has pending while the undo manager is still receptive, and then do the same before enabling registration again.

But what if you have other objects that have similar pending changes? Perhaps multiple MOCs attached to a single undo manager, or a custom class of your own. Or even just don't have a reference to the context itself handy. Well here's a simple alternative:

[[NSNotificationCenter defaultCenter]
   postNotificationName:NSUndoManagerCheckpointNotification
   object:undoManager];
[undoManager disableUndoRegistration];
// Make your special changes to the managed object
[[NSNotificationCenter defaultCenter]
   postNotificationName:NSUndoManagerCheckpointNotification
   object:undoManager];
[undoManager enableUndoRegistration];

All managed object contexts observe their undo manager's checkpoint notification since that is the correct time for them to perform standard processing of pending changes. By posting the notification yourself, it's just an easy way to flush any changes from all relevant objects.

© Mike Abdullah 2007-2009