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

Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »
Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »
Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links below... | Read more »

Price Scanner via MacPrices.net

Free iPhone 15 plus Unlimited service for $60...
Boost Infinite, part of MVNO Boost Mobile using AT&T and T-Mobile’s networks, is offering a free 128GB iPhone 15 for $60 per month including their Unlimited service plan (30GB of premium data).... Read more
$300 off any new iPhone with service at Red P...
Red Pocket Mobile has new Apple iPhones on sale for $300 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide MVNO using all the major wireless carrier... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, available for $759 for 8-Core CPU/7-Core GPU/256GB models and $929 for 8-Core CPU/8-Core GPU/512GB models. Apple’s one-year warranty is... Read more
Updated Apple MacBook Price Trackers
Our Apple award-winning MacBook Price Trackers are continually updated with the latest information on prices, bundles, and availability for 16″ and 14″ MacBook Pros along with 13″ and 15″ MacBook... Read more
Every model of Apple’s 13-inch M3 MacBook Air...
Best Buy has Apple 13″ MacBook Airs with M3 CPUs in stock and on sale today for $100 off MSRP. Prices start at $999. Their prices are the lowest currently available for new 13″ M3 MacBook Airs among... Read more
Sunday Sale: Apple iPad Magic Keyboards for 1...
Walmart has Apple Magic Keyboards for 12.9″ iPad Pros, in Black, on sale for $150 off MSRP on their online store. Sale price for online orders only, in-store price may vary. Order online and choose... Read more
Apple Watch Ultra 2 now available at Apple fo...
Apple has, for the first time, begun offering Certified Refurbished Apple Watch Ultra 2 models in their online store for $679, or $120 off MSRP. Each Watch includes Apple’s standard one-year warranty... Read more
AT&T has the iPhone 14 on sale for only $...
AT&T has the 128GB Apple iPhone 14 available for only $5.99 per month for new and existing customers when you activate unlimited service and use AT&T’s 36 month installment plan. The fine... Read more
Amazon is offering a $100 discount on every M...
Amazon is offering a $100 instant discount on each configuration of Apple’s new 13″ M3 MacBook Air, in Midnight, this weekend. These are the lowest prices currently available for new 13″ M3 MacBook... Read more
You can save $300-$480 on a 14-inch M3 Pro/Ma...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more

Jobs Board

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
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple 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
IT Systems Engineer ( *Apple* Platforms) - S...
IT Systems Engineer ( Apple Platforms) at SpaceX Hawthorne, CA SpaceX was founded under the belief that a future where humanity is out exploring the stars is 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
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.