O'Reilly logo

Beginning Mac OS® X Programming by Drew McCormack, Michael Trent

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required