TweetFollow Us on Twitter

Enhancing Your Application with NSStatusItem

Volume Number: 24 (2008)
Issue Number: 07
Column Tag: Application Development

Enhancing Your Application with NSStatusItem

How to utilize the NSStatusItem API to add functionalitys

by Marcus S. Zarra

Introduction

The user interface is arguably the hardest part of any application. This is especially true on OS X because we, as users, demand more of the developers of our applications. If the developer adds too many features and UI elements, then the application feels too busy or complicated. However if too few features are added then application is too primitive or simple.

Fortunately there are some choices. An application that would be considered too simple for the Dock might be perfect on the Dashboard or on the Menu Bar. Likewise, an application that is too busy to be a Dashboard widget might very well be perfectly at home in the Dock. But what if you are in the grey area between the Dock and the Menu Bar? While the design choices between these options ischoices between these options are beyond the scope of this article, I will present how to add a Menu Bar item – also known as a menu extra, menu item or menulet – to to your application and how to control it.

Menu Bar Items: Two Different Beasts

There are two different kinds of objects that can be placed on the menu bar in the upper right corner. First there is the kind that only Apple is allowedallows. The API is private and at the time of this article, third party developers are discouraged from using them.

The second kind that developers are encouraged to use is the NSStatusItem API. The NSStatusItem behaves decidedly different than the internal API that Apple uses. First, NSStatusItem objects cannot be dragged around the menu bar; second they cannot be removed from the menu bar with the mouse; and lastly, they are more "sluggish" than the Apple internal items when another item on the bar is moved or removed.

However, they are still an extremely useful UI element that can be utilized to great effect. The basic concept behind them is that they are a menu with an icon. In that respect, their behavior is very similar to NSMenuItem objects.

Building an NSStatusItem

While it is possible to build an NSStatusItem 100% in code, I prefer to use Interface Builder wherever whenever possible. This makes localizations easier and reduces the amount of code I need to maintain. Therefore, the first step to building an NSStatusItem is to build its menu in Interface Builder.

Building the Menu

To add a new menu to the project, I open the MainMenu.xib file and drag in a new NSMenu object (See Image 1). I normally rename the new menu to "Status Menu" or something similar to keep it clear which menu is which.


Image 1: Drag a new NSMenu into the nib

When an NSMenu is first added it contains three menu items. These items can be added to, removed from and changed as needed. For this example, I have changed the menu so that it has four items: Status, a separator, About and Quit. When I am done the menu looks like Image 2.


Image 2: The finished menu in IB

Now that the menu itself is complete it is time to write some code. For this example, the AppDelegate of my project will be responsible for the NSStatusItem. First, the header:

AppDelegate.h
#import <Cocoa/Cocoa.h>
@interface AppDelegate : NSObject {
   NSStatusItem *myStatusItem;
   IBOutlet NSMenu *myStatusMenu;
   IBOutlet NSMenuItem *myMenuStatusItem;
}
@end

Since both the about menu item and the quit menu item can be handled outside of the AppDelegate in this example, I have not added IBAction methods for them. Once the header has been written, it is time to go back to Interface Builder and link the references as shown in Image 3.

As for the About and Quit menus, they are linked to the Application object as follows:

About -> NSApplication -orderFrontStandardAboutPanel:
Quit -> NSApplication -terminate:

Once all of the linking is complete, I am done withwith the work with Interface Builder is complete;. tTime to move on to the AppDelegate. In this situation I prefer to initialize the NSStatusItem in the applicationDidFinishLaunching: method so that it appears as soon as the application is ready to start receiving events. Depending on an applications particular situation the initialization code can be placed in other locations.

AppDelegate.m
#import "AppDelegate.h"
@implementation AppDelegate
- (void)applicationDidFinishLaunching:(NSNotification*)notification
{
   myStatusItem = [[[NSStatusBar systemStatusBar] statusItemWithLength:NSSquareStatusItemLength] retain];
   
   NSImage *statusImage = [NSImage imageNamed:@"TheZ.tiff"];
   [myStatusItem setImage:statusImage];
   [myStatusItem setHighlightMode:YES];
   
   [myStatusItem setMenu:myStatusMenu];
   
   [myMenuStatusItem setTitle:NSLocalizedString(@"Special Status", @"status menu item text")];
}
@end

The first thing to notice in this code block is that NSStatusItem objects are not initialized directly. Rather, they are requested from an NSStatusBar object. The NSStatusBar object has a class level method that returns the system status bar from which I one can request a NSStatusItem.

Once I have my newthe NSStatusItem request is complete, it is possibleI am able to set its image, highlight mode and menu. The image is the image that is displayed on the Menu Bar and is has a 16x16 resolutionimage. The highlight mode determines whether or not the image is highlighted when clicked. The default is "NO", which is not appropriate when a menu is attached so I have set it to YES in the sample code. The last call to myStatusItem passes it the menu that isI constructed and referenced in Interface Builder. This will be the menu that the NSStatusItem displays when it is clicked.

The last line of the applicationDidFinishLaunching: method is a call to the status menu item that isI referenced from Interface Builder. This call changes the text of that menu item. Note that the sample code doesI have not disabled this menu. Since it does not have a target or action it will be displayed grayed out already so there is no need to disable it.

Controlling The Menu

In various situations it is appropriate to make changes to the NSStatusItem or one of its menu items. In this example, I have intentionally linked the *myStatusMenuItem ivar to one of the NSMenuItem objects on the menu so that it can be changed during the life of the program. To illustrate this change, I added a button to the main window that when clicked would change this menu item:


Image 3: Linking the AppDelegate to the Menu

AppDelegate.h
-(IBAction)changeMenu:(id)sender;
AppDelegate.m
-(IBAction)changeMenu:(id)sender;
{
  [myMenuStatusItem setTitle:NSLocalizedString(@"Changed Status", @"statuc menu item changed text")];
}

With this addition to the application, the status menu item will change to "Changed Status".

It is also possible to change the image that is displayed on the Menu Bar

AppDelegate.h
-(IBAction)purpleZ:(id)sender;
-(IBAction)blackZ:(id)sender;
AppDelegate.m
-(IBAction)purpleZ:(id)sender;
{
   [myStatusItem setImage:[NSImage imageNamed:@"ThePurpleZ.tiff"]];
}
-(IBAction)blackZ:(id)sender;
{
   [myStatusItem setImage:[NSImage imageNamed:@"TheZ.tiff"]];
}

In the example application, I added these actions are added to the Format menu rather than buttons on the main window.

Lastly, if it is desired to have the NSStatusItem as an option rather than a requirement in the application, it is possible to remove the menu item from the bar:

AppDelegate.h
-(IBAction)removeStatusItem:(id)sender;
-(IBAction)addStatusItem:(id)sender;
AppDelegate.m
-(IBAction)removeStatusItem:(id)sender;
{
   [[NSStatusBar systemStatusBar] removeStatusItem:myStatusItem];
   myStatusItem = nil;
}
-(IBAction)addStatusItem:(id)sender;
{
   if (myStatusItem) return;
   myStatusItem = [[[NSStatusBar systemStatusBar] statusItemWithLength:NSVariableStatusItemLength] retain];
   
   [myStatusItem setImage:[NSImage imageNamed:@"TheZ.tiff"]];
   [myStatusItem setHighlightMode:YES];
   [myStatusItem setMenu:myStatusMenu];
   
   [myMenuStatusItem setTitle:NSLocalizedString(@"Special Status", @"status menu item text")];
}
-(BOOL)validateMenuItem:(NSMenuItem*)item
{
   if ([item action] == @selector(removeStatusItem:)) {
      return (myStatusItem != nil);
   }
   if ([item action] == @selector(addStatusItem:)) {
      return (myStatusItem == nil);
   }
   return YES;
}

The code to remove the status item is very simple. Just one call to NSStatusBar -removeStatusItem: and it is gone. Since there is no way to add the existing item back to the bar it is prudent to set the ivar to nil at this time.

To add the NSStatusItem back to the bar, the example I simply copiesd the code from the applicationDidFinishLaunching: method. Ideally this should be abstracted so that the code is not duplicated.

Lastly, I addedthere is a -validateMenuItem: method to make sure that only one status item is ever added and just as importantly, that the application is not trying to remove a non-existent item I do not try to remove a non-existent item.

Now, with the addition of a checkbox in the preferences linked to NSUserDefaults, it is trivial to add a user preference on whether or not to show the status item. OneI could then add logic to the applicationDidFinishLaunching: method to decide whether or not a NSStatusItem needs to be initialized based on the NSUserDefault.

Conclusion

That is all there is to the NSStatusItem API. Hopefully, one day, Apple will allow third party developers to utilize their internal status items so that we can legitimately produce menu bar items that are feature comparable to the system items. Until then, NSStatusItem is a solid API that we can utilize.

As a parting comment, if I wanted my entire application to run as a menu bar item (without a Dock icon ala Twitterific), that only requires one small addition to the Info.plist:

Info.plist
<key>LSUIElement</key>
<string>1</string>

And the application will not bounce in the dock at all. I do not recommend that for this example application as it is not designed to run in that manner but there are plenty of applications that this is perfectly suited for.

NOTE: This change cannot be made to an application on the fly. So if you wanted to make the Dock icon optional also it would require an application restart and probably some trickery with the Finder as the Finder does tend to "cache" the Info.plist file for applications.


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

Tokkun Studio unveils alpha trailer for...
We are back on the MMORPG news train, and this time it comes from the sort of international developers Tokkun Studio. They are based in France and Japan, so it counts. Anyway, semantics aside, they have released an alpha trailer for the upcoming... | Read more »
Win a host of exclusive in-game Honor of...
To celebrate its latest Jujutsu Kaisen crossover event, Honor of Kings is offering a bounty of login and achievement rewards kicking off the holiday season early. [Read more] | Read more »
Miraibo GO comes out swinging hard as it...
Having just launched what feels like yesterday, Dreamcube Studio is wasting no time adding events to their open-world survival Miraibo GO. Abyssal Souls arrives relatively in time for the spooky season and brings with it horrifying new partners to... | Read more »
Ditch the heavy binders and high price t...
As fun as the real-world equivalent and the very old Game Boy version are, the Pokemon Trading Card games have historically been received poorly on mobile. It is a very strange and confusing trend, but one that The Pokemon Company is determined to... | Read more »
Peace amongst mobile gamers is now shatt...
Some of the crazy folk tales from gaming have undoubtedly come from the EVE universe. Stories of spying, betrayal, and epic battles have entered history, and now the franchise expands as CCP Games launches EVE Galaxy Conquest, a free-to-play 4x... | Read more »
Lord of Nazarick, the turn-based RPG bas...
Crunchyroll and A PLUS JAPAN have just confirmed that Lord of Nazarick, their turn-based RPG based on the popular OVERLORD anime, is now available for iOS and Android. Starting today at 2PM CET, fans can download the game from Google Play and the... | Read more »
Digital Extremes' recent Devstream...
If you are anything like me you are impatiently waiting for Warframe: 1999 whilst simultaneously cursing the fact Excalibur Prime is permanently Vault locked. To keep us fed during our wait, Digital Extremes hosted a Double Devstream to dish out a... | Read more »
The Frozen Canvas adds a splash of colou...
It is time to grab your gloves and layer up, as Torchlight: Infinite is diving into the frozen tundra in its sixth season. The Frozen Canvas is a colourful new update that brings a stylish flair to the Netherrealm and puts creativity in the... | Read more »
Back When AOL WAS the Internet – The Tou...
In Episode 606 of The TouchArcade Show we kick things off talking about my plans for this weekend, which has resulted in this week’s show being a bit shorter than normal. We also go over some more updates on our Patreon situation, which has been... | Read more »
Creative Assembly's latest mobile p...
The Total War series has been slowly trickling onto mobile, which is a fantastic thing because most, if not all, of them are incredibly great fun. Creative Assembly's latest to get the Feral Interactive treatment into portable form is Total War:... | Read more »

Price Scanner via MacPrices.net

Early Black Friday Deal: Apple’s newly upgrad...
Amazon has Apple 13″ MacBook Airs with M2 CPUs and 16GB of RAM on early Black Friday sale for $200 off MSRP, only $799. Their prices are the lowest currently available for these newly upgraded 13″ M2... Read more
13-inch 8GB M2 MacBook Airs for $749, $250 of...
Best Buy has Apple 13″ MacBook Airs with M2 CPUs and 8GB of RAM in stock and on sale on their online store for $250 off MSRP. Prices start at $749. Their prices are the lowest currently available for... Read more
Amazon is offering an early Black Friday $100...
Amazon is offering early Black Friday discounts on Apple’s new 2024 WiFi iPad minis ranging up to $100 off MSRP, each with free shipping. These are the lowest prices available for new minis anywhere... Read more
Price Drop! Clearance 14-inch M3 MacBook Pros...
Best Buy is offering a $500 discount on clearance 14″ M3 MacBook Pros on their online store this week with prices available starting at only $1099. Prices valid for online orders only, in-store... Read more
Apple AirPods Pro with USB-C on early Black F...
A couple of Apple retailers are offering $70 (28%) discounts on Apple’s AirPods Pro with USB-C (and hearing aid capabilities) this weekend. These are early AirPods Black Friday discounts if you’re... Read more
Price drop! 13-inch M3 MacBook Airs now avail...
With yesterday’s across-the-board MacBook Air upgrade to 16GB of RAM standard, Apple has dropped prices on clearance 13″ 8GB M3 MacBook Airs, Certified Refurbished, to a new low starting at only $829... Read more
Price drop! Apple 15-inch M3 MacBook Airs now...
With yesterday’s release of 15-inch M3 MacBook Airs with 16GB of RAM standard, Apple has dropped prices on clearance Certified Refurbished 15″ 8GB M3 MacBook Airs to a new low starting at only $999.... Read more
Apple has clearance 15-inch M2 MacBook Airs a...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs now available starting at $929 and ranging up to $410 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at... Read more
Apple drops prices on 13-inch M2 MacBook Airs...
Apple has dropped prices on 13″ M2 MacBook Airs to a new low of only $749 in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, now available for $679 for 8-Core CPU/7-Core GPU/256GB models. Apple’s one-year warranty is included, shipping is free, and each... Read more

Jobs Board

Seasonal Cashier - *Apple* Blossom Mall - J...
Seasonal Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Seasonal Fine Jewelry Commission Associate -...
…Fine Jewelry Commission Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) Read more
Seasonal Operations Associate - *Apple* Blo...
Seasonal Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Read more
Hair Stylist - *Apple* Blossom Mall - JCPen...
Hair Stylist - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom 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.