Undo functionality in Core Data (Swift 3)

If you’re developing a Core Data based application for Mac, wouldn’t it be great if you could add undo support?

Well, turns out that is a couple of lines away. Follow the simple steps:

1. Make sure your managedObjectContext has an undo manager, without it Core Data can’t keep track of the changes:

         managedObjectContext?.undoManager = UndoManager() 

2. In the viewController where you should handle the undo operation just add:

      func undo(_ sender: AnyObject?){

  

        coreDataHelper.managedObjectContext.undoManager?.undo()

 

        refreshTable() //If applicable (for instance if you don’t use bindings)

        re-fetch the information and reload the table. This is what this

        function does in my code

 

      }

And that’s it, now you have full undo functionality! You’ll see how in the menus Undo no longer appears greyed out.

Questions / comments? I’m at @MarcMasVi 

Marc