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

Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links... | Read more »
Price of Glory unleashes its 1.4 Alpha u...
As much as we all probably dislike Maths as a subject, we do have to hand it to geometry for giving us the good old Hexgrid, home of some of the best strategy games. One such example, Price of Glory, has dropped its 1.4 Alpha update, stocked full... | Read more »
The SLC 2025 kicks off this month to cro...
Ever since the Solo Leveling: Arise Championship 2025 was announced, I have been looking forward to it. The promotional clip they released a month or two back showed crowds going absolutely nuts for the previous competitions, so imagine the... | Read more »
Dive into some early Magicpunk fun as Cr...
Excellent news for fans of steampunk and magic; the Precursor Test for Magicpunk MMORPG Crystal of Atlan opens today. This rather fancy way of saying beta test will remain open until March 5th and is available for PC - boo - and Android devices -... | Read more »
Prepare to get your mind melted as Evang...
If you are a fan of sci-fi shooters and incredibly weird, mind-bending anime series, then you are in for a treat, as Goddess of Victory: Nikke is gearing up for its second collaboration with Evangelion. We were also treated to an upcoming... | Read more »
Square Enix gives with one hand and slap...
We have something of a mixed bag coming over from Square Enix HQ today. Two of their mobile games are revelling in life with new events keeping them alive, whilst another has been thrown onto the ever-growing discard pile Square is building. I... | Read more »
Let the world burn as you have some fest...
It is time to leave the world burning once again as you take a much-needed break from that whole “hero” lark and enjoy some celebrations in Genshin Impact. Version 5.4, Moonlight Amidst Dreams, will see you in Inazuma to attend the Mikawa Flower... | Read more »
Full Moon Over the Abyssal Sea lands on...
Aether Gazer has announced its latest major update, and it is one of the loveliest event names I have ever heard. Full Moon Over the Abyssal Sea is an amazing name, and it comes loaded with two side stories, a new S-grade Modifier, and some fancy... | Read more »
Open your own eatery for all the forest...
Very important question; when you read the title Zoo Restaurant, do you also immediately think of running a restaurant in which you cook Zoo animals as the course? I will just assume yes. Anyway, come June 23rd we will all be able to start up our... | Read more »
Crystal of Atlan opens registration for...
Nuverse was prominently featured in the last month for all the wrong reasons with the USA TikTok debacle, but now it is putting all that behind it and preparing for the Crystal of Atlan beta test. Taking place between February 18th and March 5th,... | Read more »

Price Scanner via MacPrices.net

AT&T is offering a 65% discount on the ne...
AT&T is offering the new iPhone 16e for up to 65% off their monthly finance fee with 36-months of service. No trade-in is required. Discount is applied via monthly bill credits over the 36 month... Read more
Use this code to get a free iPhone 13 at Visi...
For a limited time, use code SWEETDEAL to get a free 128GB iPhone 13 Visible, Verizon’s low-cost wireless cell service, Visible. Deal is valid when you purchase the Visible+ annual plan. Free... Read more
M4 Mac minis on sale for $50-$80 off MSRP at...
B&H Photo has M4 Mac minis in stock and on sale right now for $50 to $80 off Apple’s MSRP, each including free 1-2 day shipping to most US addresses: – M4 Mac mini (16GB/256GB): $549, $50 off... Read more
Buy an iPhone 16 at Boost Mobile and get one...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering one year of free Unlimited service with the purchase of any iPhone 16. Purchase the iPhone at standard MSRP, and then choose... Read more
Get an iPhone 15 for only $299 at Boost Mobil...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering the 128GB iPhone 15 for $299.99 including service with their Unlimited Premium plan (50GB of premium data, $60/month), or $20... Read more
Unreal Mobile is offering $100 off any new iP...
Unreal Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering a $100 discount on any new iPhone with service. This includes new iPhone 16 models as well as iPhone 15, 14, 13, and SE... Read more
Apple drops prices on clearance iPhone 14 mod...
With today’s introduction of the new iPhone 16e, Apple has discontinued the iPhone 14, 14 Pro, and SE. In response, Apple has dropped prices on unlocked, Certified Refurbished, iPhone 14 models to a... Read more
B&H has 16-inch M4 Max MacBook Pros on sa...
B&H Photo is offering a $360-$410 discount on new 16-inch MacBook Pros with M4 Max CPUs right now. B&H offers free 1-2 day shipping to most US addresses: – 16″ M4 Max MacBook Pro (36GB/1TB/... Read more
Amazon is offering a $100 discount on the M4...
Amazon has the M4 Pro Mac mini discounted $100 off MSRP right now. Shipping is free. Their price is the lowest currently available for this popular mini: – Mac mini M4 Pro (24GB/512GB): $1299, $100... Read more
B&H continues to offer $150-$220 discount...
B&H Photo has 14-inch M4 MacBook Pros on sale for $150-$220 off MSRP. B&H offers free 1-2 day shipping to most US addresses: – 14″ M4 MacBook Pro (16GB/512GB): $1449, $150 off MSRP – 14″ M4... Read more

Jobs Board

All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.