8.9. Handling Undo

The capability to easily undo or redo any change is a requirement for any application that considers itself user-friendly. Undo encourages users to experiment with your application's features. If they get into trouble they simply press Command-Z and their last change is undone.

Cocoa's document architecture provides support for undo and redo in your documents. But like other aspects of the document architecture, you must manage the finer details yourself. And that's only natural as every application handles their data differently.

In the following Try It Out, you add simple undo and redo support to Slide Master. The SlideShowDocument records the state of its mSlides list before every operation that changes that list. An undo operation is simply a matter of replacing the document's slide list with the one recorded earlier. This approach isn't particularly elegant or efficient, but it is simple.

8.9.1.

8.9.1.1. Try It Out: Handling Undo and Redo
  1. In Xcode, open SlideShowDocument.m and add the following methods to SlideShowDocument's PrivateMethods category:

    - (void)recordSlideChange;
    - (void)handleUndo:(id)object;
  2. Call the recordSlideChange method before you change the mSlides list in addSlidesAtPaths: and removeSlidesAtIndexes:. The relevant part of addSlidesAtPaths: is shown in the following code:

    if ([newSlides count]) {
            [self recordSlideChange];
    
            [mSlides addObjectsFromArray:newSlides];
    
            [self notifySlidesChanged];
        }
  3. Add the following code to the end of SlideShowDocument ...

Get Beginning Mac OS® X Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.