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

Go from lowly lizard to wicked Wyvern in...
Do you like questing, and do you like dragons? If not then boy is this not the announcement for you, as Loongcheer Game has unveiled Quest Dragon: Idle Mobile Game. Yes, it is amazing Square Enix hasn’t sued them for copyright infringement, but... | Read more »
Aether Gazer unveils Chapter 16 of its m...
After a bit of maintenance, Aether Gazer has released Chapter 16 of its main storyline, titled Night Parade of the Beasts. This big update brings a new character, a special outfit, some special limited-time events, and, of course, an engaging... | Read more »
Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »
Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »

Price Scanner via MacPrices.net

Limited-time sale: 13-inch M3 MacBook Airs fo...
Amazon has the base 13″ M3 MacBook Air (8GB/256GB) in stock and on sale for a limited time for $989 shipped. That’s $110 off MSRP, and it’s the lowest price we’ve seen so far for an M3-powered... Read more
13-inch M2 MacBook Airs in stock today at App...
Apple has 13″ M2 MacBook Airs available for only $849 today in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty is included,... Read more
New today at Apple: Series 9 Watches availabl...
Apple is now offering Certified Refurbished Apple Watch Series 9 models on their online store for up to $80 off MSRP, starting at $339. Each Watch includes Apple’s standard one-year warranty, a new... Read more
The latest Apple iPhone deals from wireless c...
We’ve updated our iPhone Price Tracker with the latest carrier deals on Apple’s iPhone 15 family of smartphones as well as previous models including the iPhone 14, 13, 12, 11, and SE. Use our price... Read more
Boost Mobile will sell you an iPhone 11 for $...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering an iPhone 11 for $149.99 when purchased with their $40 Unlimited service plan (12GB of premium data). No trade-in is required... Read more
Free iPhone 15 plus Unlimited service for $60...
Boost Infinite, part of MVNO Boost Mobile using AT&T and T-Mobile’s networks, is offering a free 128GB iPhone 15 for $60 per month including their Unlimited service plan (30GB of premium data).... Read more
$300 off any new iPhone with service at Red P...
Red Pocket Mobile has new Apple iPhones on sale for $300 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide MVNO using all the major wireless carrier... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, available for $759 for 8-Core CPU/7-Core GPU/256GB models and $929 for 8-Core CPU/8-Core GPU/512GB models. Apple’s one-year warranty is... Read more
Updated Apple MacBook Price Trackers
Our Apple award-winning MacBook Price Trackers are continually updated with the latest information on prices, bundles, and availability for 16″ and 14″ MacBook Pros along with 13″ and 15″ MacBook... Read more
Every model of Apple’s 13-inch M3 MacBook Air...
Best Buy has Apple 13″ MacBook Airs with M3 CPUs in stock and on sale today for $100 off MSRP. Prices start at $999. Their prices are the lowest currently available for new 13″ M3 MacBook Airs among... Read more

Jobs Board

Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
DMR Technician - *Apple* /iOS Systems - Haml...
…relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple 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.