Application Resume on Mac OS X Lion

Application Resume on Mac OS X Lion is a really nice feature that ties into the theme of hiding the details of the application runtime cycle from the user. We already see this on iOS and I am a big fan of it. It is not hard to implement and, I feel, well worth the time to do so.

Restorable Checkbox

Make sure the checkbox for Restorable is checked for the window you want to preserve in its nib file. Simply having that checked will automatically save the size and position of the window and the state of the the responder objects. But you will need to preserve more than this, which you do by implementing two window delegate methods, window: willEncodeRestorableState: and window: didDecodeRestorableState:.

// User Interface Preservation. Window Delegate.
- (void)window:(NSWindow *)window willEncodeRestorableState:(NSCoder *)state {
    NSIndexPath *indexPath = _currentSelectionTree.selectionIndexPath;

    [state encodeObject:indexPath forKey:@"BPSelectionIndexPath"];

In the code above, I am preserving the selection state of a NSTreeController. You can encode anything you want in here, but it is very important to remember that this is not meant for saving user data. If something happens, you may very well never see it again, so it is only to be used for window state information.

// User Interface Preservation. Window Delegate.
- (void)window:(NSWindow *)window didDecodeRestorableState:(NSCoder *)state {

    NSError *error = nil;
    BOOL ok = [_currentSelectionTree fetchWithRequest:nil merge:NO error:&error];
    if( ok ) {
        NSIndexPath *indexPath = [state decodeObjectForKey:@"BPSelectionIndexPath"];

        _currentSelectionTree.selectionIndexPath = indexPath;

And here we have the code that restores state. The reason we call fetchWithRequest on the _currentSelectionTree is to make sure that it has been loaded from the nib before we try to use it.

For more information, see the Apple documentation for User Interface Preservation.

Question or Comment?