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.