TweetFollow Us on Twitter

Grokking OS X's Undo Support

Volume Number: 24 (2008)
Issue Number: 04
Column Tag: Programming

Grokking OS X's Undo Support

How to effectively use the Undo Manager built into Cocoa

by Marcus S. Zarra

Introduction

One of the great benefits of working with Cocoa is that the APIs give the developer numerous features "for free". One of those features is undo support. Any Cocoa application, without any work from the developer, will automatically get undo support at some basic level. In this article I walk through exactly how Undo support works in Cocoa and how you as the developer can take some control over undo to provide the functionality you are looking for.

Overview

Undo is one of those features that is rarely thought about. Most developers do not check it off as a feature in their application and most users do not immediately look for it when reviewing a new application. However, it is a feature that if not present when you need it, it is sorely missed. Fortunately, Apple has recognized this and included undo support for the developer so that, in most cases, we do not need to think about it.

Unfortunately, when your application strays from the beaten path then you need to roll up your sleeves and make sure that undo support works exactly as you expect it to. As it is said, the devil is in the details, and having inconsistent undo support is worse than having none at all.

What is Undo?

Apple defines undo as:

An undo operation is a method for reverting a change to an object, along with the arguments needed to revert the change (for example, its state before the change)

Undo is performed on a stack. What this means to those not familiar with the term is that each action, or event, that is "undoable" is added to the top of the stack and therefore can be removed from the stack. When you remove an item from the stack it is also removed from the top and thus reversing the order it was added. For example, if you were editing a paragraph of text in a Cocoa NSTextArea and you typed "Hello World", that text would be added to the stack as an undoable event. If you then selected "Hello" and hit ?B, the text would become bold and the action of bolding that selection of text would be added to the stack.


The reason that the "stack" aspect of this is important is when you want to undo something. When you choose undo then the first time is removed from the top of the stack (in this example, the bolding of "Hello") and undone. If the items were processed in a FIFO (First In, First Out) order then the text would be deleted instead, which is definitely not what the user would expect to happen.

The Undo Stack

What exactly is the stack? Probably the easiest way to describe the stack is to describe how to put things onto it. As an example, lets say that we have a value that we want to be undoable and therefore we want to add any changes to that value to the stack. To do that we would perform the following:

-(void)setName:(NSString*)newName;;
{
   [[self undoManager] registerUndoWithTarget:self 
      selector:@selector(setName:) 
      object:[self name]];
   [newName retain];
   [name release];
   name = newName;
}

For those familiar with Cocoa/Objective-C, this is a fairly standard setter call to set the attribute name. The change from the normal is the additional call to the NSUndoManager. Note that in this example I am passing it a reference to the object to call the method on (self), the method name to call (setName:) and the previous value of that attribute.

Internally, the NSUndoManager, is going to remember these values that you are passing in and retain them as an undo event. That event will then be stored on a stack (presumably in an NSArray) to be recalled at a later time. Therefore the stack is really an array of structures/objects that reference a target, a selector and another object. One thing that is interesting in this design is that the object (the previous value of name) is actually retained by the undo event. This guarantees that the value will still be around if the undo event is ever invoked.

When the user of the application invokes the undo command, the last item added to the NSUndoManager is retrieved and then the selector is called upon the target with the object that is being passed in, thereby reversing the event. Of note: When an event is removed from the undo stack, it is automatically added to the redo stack. This allows a user to undo and redo their actions as needed.

Grouping Undo

In addition to being able to undo and redo individual events such as the setter above, it is possible to group individual events together so that they are undone and redone as a single operation. An example of this would be an extension of the example above. For instance, lets imagine that the setName: method above actually breaks the string apart into a first name and last name. And instead of having an undo registration at the setName, we want to have the first and last name register events, then grouping would come into play when the full name is set.

-(void)setName:(NSString*)name;
{
   [[self undoManager] beginUndoGrouping];
   NSArray *words = [name componentsSeparatedByString@" "];
   [self setFirstName:[words objectAtIndex:0];
   [self setLastName:[words objectAtIndex:1];
   [[self undoManager] endUndoGrouping];
}
- (void)setFirstName:(NSString*)name
{
   [[self undoManager] registerUndoWithTarget:self 
      selector:@selector(setFirstName:) 
      object:[self firstName]];
   [name retain];
   [firstName release];
   firstName = name;
}
- (void)setLastName:(NSString*)name
{
   [[self undoManager] registerUndoWithTarget:self
      selector:@selector(setLastName:)
      object:[self lastName]];
   [name retain];
   [lastName release];
   lastName = name;
}

As can be seen in the listing, the individual parts of the name have stored their changes in the NSUndoManager's stack but the setName: method does not store its changes in the undo stack. Instead, it starts a group, sets the individual components and then ends the grouping. What this does is still the NSUndoManager that all undo events it receives between the begin and end are to be performed together. By using grouping in an example like this you do not risk polluting the stack with a setName:, setFirstName: and setLastName: call and thereby causing an issue when the user attempts to undo the action.

Naming the event

In addition to being able to control the undo/redo events, it is also possible to name these events. That name is then used by the undo and redo menu items to help explain to the user exactly what they will be undoing and redoing.

- (void)setFirstName:(NSString*)name
{
   [[self undoManager] registerUndoWithTarget:self 
      selector:@selector(setFirstName:) 
      object:[self firstName]];
   [[self undoManager] setActionName:
      NSLocalizedString(@"First Name", 
      @"First Name undo action")];
   [name retain];
   [firstName release];
   firstName = name;
}

The only change from the previous example is the addition of [undoManager setActionName:]. This call instructs the NSUndoManager to attach the passed in string as the name of the previous event. In this example, it attaches the name of "First Name" to the event of setFirstName:. If the user were to look in the edit menu after changing the first name they would see something like "Undo First Name". As you can see, we localized the action name so that we can easily go back and localize the name of the action at a later time.

It should be noted that groupings can also be named. If an event and a grouping are both named then the grouping name will win out. For example, if our setName: method also set the ActionName to "Name" then when the setName: method is called the edit menu would display "Undo Name" and not "Undo First Name" or "Undo Last Name".

Levels of Undo

As can be expected, since the NSUndoManager actually retains the objects being passed around it is quite possible to begin to have a memory issue. This is especially true if the object of the function call is in itself quite large. One option to help contain this is to limit the number or "levels" of undo available to the application. This is controlled by a simple call to:

[[self undoManager] setLevelsOfUndo:10];

which will limit the application to remembering only the last 10 undo events.

Blocking Undo Support

As you can probably imagine, since undo support is managed as such a low level (all the way down in the setters), it is possible to build up a large undo stack just by populating an object from another source. Fortunately, there is a way to avoid this. For example, imagine you are populating our example object from an XML feed. Naturally, you do not want to start building up the undo stack while setting the values from the xml document but you do want to add to the stack when a user changes something. How can you instruct your application to tell the difference?

The secret is to pause the undo registration while loading your document and then resuming it after your load is complete. See the following example:

- (MyObject*)buildMyObjectFromXML:(NSXMLDocument*)doc
{
   NSString *tempFirstName = ...;
   NSString *tempLastName = ...;
   NSUndoManager *undo = [self undoManager];
   [undo disableUndoRegistration];
   MyObject *object = [[MyObject alloc] init];
   [object setFirstName:tempFirstName];
   [object setLastName:tempLastName];
   [undo enableUndoRegistration];
   return [object autorelease];
}

In this example, we instruct the NSUndoManager to stop registering events and then we build the data object and set its attributes. The data object itself has no knowledge of whether or not the NSUndoManager is disabled (although we could check if needed for some reason) and continues to register events. The NSUndoManager receives these events and since it is disabled simply throws them away. When the object has been completely loaded we then turn the registration back on so that any events afterwards will be registered properly.

Initializing the NSUndoManager

In all of these examples, I have just been calling [self undoManager] to get a reference to the NSUndoManager. In an actual program you should have very few NSUndoManagers. Each NSUndoManager should be in a logical location. For instance, if you have a document style application then each document should have its own NSUndoManager. Otherwise you probably only want one NSUndoManager for the entire application.

To initialize an NSUndoManager, you simply call:

NSUndoManager *undoManager = [[NSUndoManger alloc] init];

Naturally, you are going to want to hold onto a reference to this object so that you can make it available to other parts of your application.

Getting the UI to use your NSUndoManager

If you are going to build and/or use your own NSUndoManager then you will want to let the user interface access that same NSUndoManager to avoid having multiple stacks trying to act on the same data. Fortunately, all views get their NSUndoManager from their window and the window gets its NSUndoManager from its delegate. Therefore if you have set up your controller (or another object) as the delegate for your window, add the following method call:

- (NSUndoManager *)windowWillReturnUndoManager:(NSWindow *)window
{
   return [self undoManager];
}

The window will then call this method to get its NSUndoManager. If you do not supply a delegate then the window will initialize its own NSUndoManager.

Conclusion

Once the curtain has been pulled back you can see that the NSUndoManager is in fact a simple array containing structures with two objects and a selector. That is all there is to Undo. However that simplicity belies the power of the design. The application of that simple data structure allows for the sense of wonder and awe that is an application with a properly implemented undo subsystem.


Marcus S. Zarra is the owner of Zarra Studios, based out of Colorado Springs, Colorado. He has been developing Cocoa software since 2003, Java software since 1996, and has been in the industry since 1985. Currently Marcus is producing software for OS X. In addition to writing software, he assists other developers by blogging about development and supplying code samples.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Jump into one of Volkswagen's most...
We spoke about PUBG Mobile yesterday and their Esports development, so it is a little early to revisit them, but we have to because this is just too amusing. Someone needs to tell Krafton that PUBG Mobile is a massive title because out of all the... | Read more »
PUBG Mobile will be releasing more ways...
The emergence of Esports is perhaps one of the best things to happen in gaming. It shows our little hobby can be a serious thing, gets more people intrigued, and allows players to use their skills to earn money. And on that last point, PUBG Mobile... | Read more »
Genshin Impact 5.1 launches October 9th...
If you played version 5.0 of Genshin Impact, you would probably be a bit bummed by the lack of a Pyro version of the Traveller. Well, annoyingly HoYo has stopped short of officially announcing them in 5.1 outside a possible sighting in livestream... | Read more »
A Phoenix from the Ashes – The TouchArca...
Hello! We are still in a transitional phase of moving the podcast entirely to our Patreon, but in the meantime the only way we can get the show’s feed pushed out to where it needs to go is to post it to the website. However, the wheels are in motion... | Read more »
Race with the power of the gods as KartR...
I have mentioned it before, somewhere in the aether, but I love mythology. Primarily Norse, but I will take whatever you have. Recently KartRider Rush+ took on the Arthurian legends, a great piece of British mythology, and now they have moved on... | Read more »
Tackle some terrifying bosses in a new g...
Blue Archive has recently released its latest update, packed with quite an arsenal of content. Named Rowdy and Cheery, you will take part in an all-new game mode, recruit two new students, and follow the team's adventures in Hyakkiyako. [Read... | Read more »
Embrace a peaceful life in Middle-Earth...
The Lord of the Rings series shows us what happens to enterprising Hobbits such as Frodo, Bilbo, Sam, Merry and Pippin if they don’t stay in their lane and decide to leave the Shire. It looks bloody dangerous, which is why September 23rd is an... | Read more »
Athena Crisis launches on all platforms...
Athena Crisis is a game I have been following during its development, and not just because of its brilliant marketing genius of letting you play a level on the webpage. Well for me, and I assume many of you, the wait is over as Athena Crisis has... | Read more »
Victrix Pro BFG Tekken 8 Rage Art Editio...
For our last full controller review on TouchArcade, I’ve been using the Victrix Pro BFG Tekken 8 Rage Art Edition for PC and PlayStation across my Steam Deck, PS5, and PS4 Pro for over a month now. | Read more »
Matchday Champions celebrates early acce...
Since colossally shooting themselves in the foot with a bazooka and fumbling their deal with EA Sports, FIFA is no doubt scrambling for other games to plaster its name on to cover the financial blackhole they made themselves. Enter Matchday, with... | Read more »

Price Scanner via MacPrices.net

Apple Watch Ultra available today at Apple fo...
Apple has several Certified Refurbished Apple Watch Ultra models available in their online store for $589, or $210 off original MSRP. Each Watch includes Apple’s standard one-year warranty, a new... Read more
Amazon is offering coupons worth up to $109 o...
Amazon is offering clippable coupons worth up to $109 off MSRP on certain Silver and Blue M3-powered 24″ iMacs, each including free shipping. With the coupons, these iMacs are $150-$200 off Apple’s... Read more
Amazon is offering coupons to take up to $50...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for up to $110 off MSRP, each including free delivery. Prices are valid after free coupons available on each mini’s product page, detailed... Read more
Use your Education discount to take up to $10...
Need a new Apple iPad? If you’re a student, teacher, or staff member at any educational institution, you can use your .edu email address when ordering at Apple Education to take up to $100 off the... Read more
Apple has 15-inch M2 MacBook Airs available f...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs available starting at $1019 and ranging up to $300 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at Apple.... Read more
Mac Studio with M2 Max CPU on sale for $1749,...
B&H Photo has the standard-configuration Mac Studio model with Apple’s M2 Max CPU in stock today and on sale for $250 off MSRP, now $1749 (12-Core CPU and 32GB RAM/512GB SSD). B&H offers... Read more
Save up to $260 on a 15-inch M3 MacBook Pro w...
Apple has Certified Refurbished 15″ M3 MacBook Airs in stock today starting at only $1099 and ranging up to $260 off MSRP. These are the cheapest M3-powered 15″ MacBook Airs for sale today at Apple.... Read more
Apple has 16-inch M3 Pro MacBook Pro in stock...
Apple has a full line of 16″ M3 Pro MacBook Pros available, Certified Refurbished, starting at $2119 and ranging up to $440 off MSRP. Each model features a new outer case, shipping is free, and an... Read more
Apple M2 Mac minis on sale for $120-$200 off...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for $110-$200 off MSRP this weekend, each including free delivery: – Mac mini M2/256GB SSD: $469, save $130 – Mac mini M2/512GB SSD: $689.... Read more
Clearance 9th-generation iPads are in stock t...
Best Buy has Apple’s 9th generation 10.2″ WiFi iPads on clearance sale for starting at only $199 on their online store for a limited time. Sale prices for online orders only, in-store prices may vary... Read more

Jobs Board

Senior Mobile Engineer-Android/ *Apple* - Ge...
…Trust/Other Required:** NACI (T1) **Job Family:** Systems Engineering **Skills:** Apple Devices,Device Management,Mobile Device Management (MDM) **Experience:** 10 + Read more
Sonographer - *Apple* Hill Imaging Center -...
Sonographer - Apple Hill Imaging Center - Evenings Location: York Hospital, York, PA Schedule: Full Time Full Time (80 hrs/pay period) Evenings General Summary Read more
*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.