Creating Status Items

You obtain the system status bar with the systemStatusBar class method; do not allocate an instance yourself. Invoke statusItemWithLength: to create a new status item and allocate space for it in the menu bar. Pass the amount of space in pixels you need to display your status item. You can use the constants NSSquareStatusItemLength or NSVariableStatusItemLength to make the width the same as the status bar’s thickness (as returned by the method thickness) or variable based on the contents of the item, respectively. Use the former if you are displaying an icon and the latter if you are displaying static text.

Because the system status bar is shared by all applications, it cannot retain references to each application’s status item objects. Instead, each application is responsible for retaining its own status items. Each status item then communicates with the status bar as its configuration changes. When deallocated, the status item removes itself from the status bar. Following normal Cocoa memory management rules, you must retain the object returned by statusItemWithLength: to keep it around.

Once you have the new status item object, you can assign it a title, a menu, a target-action, a tool tip, and so on.

In the following example, a status item is added to the menu bar and assigned a menu.

- (void)activateStatusMenu
    NSStatusBar *bar = [NSStatusBar systemStatusBar];
    theItem = [bar statusItemWithLength:NSVariableStatusItemLength];
    [theItem retain];
    [theItem setTitle: NSLocalizedString(@"Tablet",@"")];
    [theItem setHighlightMode:YES];
    [theItem setMenu:theMenu];

In this code example, assume your object has an instance variable, theMenu, that holds an NSMenu object, perhaps unarchived from a nib file. Another instance variable, theItem, holds the status item, which is retained. When you execute this code, a menu titled “Tablet” (or a localized version if available) is added to the right side of the menu bar. The menu is available from within every application as long as your application is running and the status item exists.