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

Recruit two powerful-sounding students t...
I am a fan of anime, and I hear about a lot that comes through, but one that escaped my attention until now is A Certain Scientific Railgun T, and that name is very enticing. If it's new to you too, then players of Blue Archive can get a hands-on... | Read more »
Top Hat Studios unveils a new gameplay t...
There are a lot of big games coming that you might be excited about, but one of those I am most interested in is Athenian Rhapsody because it looks delightfully silly. The developers behind this project, the rather fancy-sounding Top Hat Studios,... | Read more »
Bound through time on the hunt for sneak...
Have you ever sat down and wondered what would happen if Dr Who and Sherlock Holmes went on an adventure? Well, besides probably being the best mash-up of English fiction, you'd get the Hidden Through Time series, and now Rogueside has announced... | Read more »
The secrets of Penacony might soon come...
Version 2.2 of Honkai: Star Rail is on the horizon and brings the culmination of the Penacony adventure after quite the escalation in the latest story quests. To help you through this new expansion is the introduction of two powerful new... | Read more »
The Legend of Heroes: Trails of Cold Ste...
I adore game series that have connecting lore and stories, which of course means the Legend of Heroes is very dear to me, Trails lore has been building for two decades. Excitedly, the next stage is upon us as Userjoy has announced the upcoming... | Read more »
Go from lowly lizard to wicked Wyvern in...
Do you like questing, and do you like dragons? If not then boy is this not the announcement for you, as Loongcheer Game has unveiled Quest Dragon: Idle Mobile Game. Yes, it is amazing Square Enix hasn’t sued them for copyright infringement, but... | Read more »
Aether Gazer unveils Chapter 16 of its m...
After a bit of maintenance, Aether Gazer has released Chapter 16 of its main storyline, titled Night Parade of the Beasts. This big update brings a new character, a special outfit, some special limited-time events, and, of course, an engaging... | Read more »
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 »

Price Scanner via MacPrices.net

May 2024 Apple Education discounts on MacBook...
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 $300 off the purchase of a new MacBook... Read more
Clearance 16-inch M2 Pro MacBook Pros in stoc...
Apple has clearance 16″ M2 Pro MacBook Pros available in their Certified Refurbished store starting at $2049 and ranging up to $450 off original MSRP. Each model features a new outer case, shipping... Read more
Save $300 at Apple on 14-inch M3 MacBook Pros...
Apple has 14″ M3 MacBook Pros with 16GB of RAM, Certified Refurbished, available for $270-$300 off MSRP. Each model features a new outer case, shipping is free, and an Apple 1-year warranty is... Read more
Apple continues to offer 14-inch M3 MacBook P...
Apple has 14″ M3 MacBook Pros, Certified Refurbished, available starting at only $1359 and ranging up to $270 off MSRP. Each model features a new outer case, shipping is free, and an Apple 1-year... Read more
Apple AirPods Pro with USB-C return to all-ti...
Amazon has Apple’s AirPods Pro with USB-C in stock and on sale for $179.99 including free shipping. Their price is $70 (28%) off MSRP, and it’s currently the lowest price available for new AirPods... Read more
Apple Magic Keyboards for iPads are on sale f...
Amazon has Apple Magic Keyboards for iPads on sale today for up to $70 off MSRP, shipping included: – Magic Keyboard for 10th-generation Apple iPad: $199, save $50 – Magic Keyboard for 11″ iPad Pro/... Read more
Apple’s 13-inch M2 MacBook Airs return to rec...
Apple retailers have 13″ MacBook Airs with M2 CPUs in stock and on sale this weekend starting at only $849 in Space Gray, Silver, Starlight, and Midnight colors. These are the lowest prices currently... Read more
Best Buy is clearing out iPad Airs for up to...
In advance of next week’s probably release of new and updated iPad Airs, Best Buy has 10.9″ M1 WiFi iPad Airs on record-low sale prices for up to $200 off Apple’s MSRP, starting at $399. Sale prices... Read more
Every version of Apple Pencil is on sale toda...
Best Buy has all Apple Pencils on sale today for $79, ranging up to 39% off MSRP for some models. Sale prices for online orders only, in-store prices may vary. Order online and choose free shipping... Read more
Sunday Sale: Apple Studio Display with Standa...
Amazon has the standard-glass Apple Studio Display on sale for $300 off MSRP for a limited time. Shipping is free: – Studio Display (Standard glass): $1299.97 $300 off MSRP For the latest prices and... Read more

Jobs Board

Liquor Stock Clerk - S. *Apple* St. - Idaho...
Liquor Stock Clerk - S. Apple St. Boise Posting Begin Date: 2023/10/10 Posting End Date: 2024/10/14 Category: Retail Sub Category: Customer Service Work Type: Part Read more
*Apple* App Developer - Datrose (United Stat...
…year experiencein programming and have computer knowledge with SWIFT. Job Responsibilites: Apple App Developer is expected to support essential tasks for the RxASL 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
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
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.