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

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 »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »
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 below... | Read more »
Marvel Future Fight celebrates nine year...
Announced alongside an advertising image I can only assume was aimed squarely at myself with the prominent Deadpool and Odin featured on it, Netmarble has revealed their celebrations for the 9th anniversary of Marvel Future Fight. The Countdown... | Read more »
HoYoFair 2024 prepares to showcase over...
To say Genshin Impact took the world by storm when it was released would be an understatement. However, I think the most surprising part of the launch was just how much further it went than gaming. There have been concerts, art shows, massive... | Read more »
Explore some of BBCs' most iconic s...
Despite your personal opinion on the BBC at a managerial level, it is undeniable that it has overseen some fantastic British shows in the past, and now thanks to a partnership with Roblox, players will be able to interact with some of these... | Read more »
Play Together teams up with Sanrio to br...
I was quite surprised to learn that the massive social network game Play Together had never collaborated with the globally popular Sanrio IP, it seems like the perfect team. Well, this glaring omission has now been rectified, as that instantly... | Read more »

Price Scanner via MacPrices.net

B&H has 13-inch M2 MacBook Airs with 16GB...
B&H Photo has 13″ MacBook Airs with M2 CPUs, 16GB of memory, and 256GB of storage in stock and on sale for $1099, $100 off Apple’s MSRP for this configuration. Free 1-2 day delivery is available... Read more
14-inch M3 MacBook Pro with 16GB of RAM avail...
Apple has the 14″ M3 MacBook Pro with 16GB of RAM and 1TB of storage, Certified Refurbished, available for $300 off MSRP. Each MacBook Pro features a new outer case, shipping is free, and an Apple 1-... Read more
Apple M2 Mac minis on sale for up to $150 off...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for $100-$150 off MSRP, each including free delivery: – Mac mini M2/256GB SSD: $499, save $100 – Mac mini M2/512GB SSD: $699, save $100 –... Read more
Amazon is offering a $200 discount on 14-inch...
Amazon has 14-inch M3 MacBook Pros in stock and on sale for $200 off MSRP. Shipping is free. Note that Amazon’s stock tends to come and go: – 14″ M3 MacBook Pro (8GB RAM/512GB SSD): $1399.99, $200... Read more
Sunday Sale: 13-inch M3 MacBook Air for $999,...
Several Apple retailers have the new 13″ MacBook Air with an M3 CPU in stock and on sale today for only $999 in Midnight. These are the lowest prices currently available for new 13″ M3 MacBook Airs... Read more
Multiple Apple retailers are offering 13-inch...
Several Apple retailers have 13″ MacBook Airs with M2 CPUs in stock and on sale this weekend starting at only $849 in Space Gray, Silver, Starlight, and Midnight colors. These are the lowest prices... Read more
Roundup of Verizon’s April Apple iPhone Promo...
Verizon is offering a number of iPhone deals for the month of April. Switch, and open a new of service, and you can qualify for a free iPhone 15 or heavy monthly discounts on other models: – 128GB... Read more
B&H has 16-inch MacBook Pros on sale for...
Apple 16″ MacBook Pros with M3 Pro and M3 Max CPUs are in stock and on sale today for $200-$300 off MSRP at B&H Photo. Their prices are among the lowest currently available for these models. B... Read more
Updated Mac Desktop Price Trackers
Our Apple award-winning Mac desktop price trackers are the best place to look for the lowest prices and latest sales on all the latest computers. Scan our price trackers for the latest information on... Read more
9th-generation iPads on sale for $80 off MSRP...
Best Buy has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80 off MSRP on their online store for a limited time. Prices start at only $249. Sale prices for online orders only, in-store prices... Read more

Jobs Board

*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
Liquor Stock Clerk - S. *Apple* St. - Idaho...
Liquor Stock Clerk - S. Apple St. Boise Posting Begin Date: 2023/10/10 Posting End Date: 2024/10/14 Category: Retail Sub Category: Customer Service Work Type: Part Read more
Top Secret *Apple* System Admin - Insight G...
Job Description Day to Day: * Configure and maintain the client's Apple Device Management (ADM) solution. The current solution is JAMF supporting 250-500 end points, Read more
Sonographer - *Apple* Hill Imaging Center -...
Sonographer - Apple Hill Imaging Center - Evenings Location: York Hospital, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Now Read more
Beauty Consultant - *Apple* Blossom Mall -...
Beauty Consultant - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.