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

The secrets of Penacony might soon come...
Version 2.2 of Honkai: Star Rail is on the horizon and brings the culmination of the Penacony adventure after quite the escalation in the latest story quests. To help you through this new expansion is the introduction of two powerful new... | Read more »
The Legend of Heroes: Trails of Cold Ste...
I adore game series that have connecting lore and stories, which of course means the Legend of Heroes is very dear to me, Trails lore has been building for two decades. Excitedly, the next stage is upon us as Userjoy has announced the upcoming... | Read more »
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 »

Price Scanner via MacPrices.net

Apple Magic Keyboards for iPads are on sale f...
Amazon has Apple Magic Keyboards for iPads on sale today for up to $70 off MSRP, shipping included: – Magic Keyboard for 10th-generation Apple iPad: $199, save $50 – Magic Keyboard for 11″ iPad Pro/... Read more
Apple’s 13-inch M2 MacBook Airs return to rec...
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 currently... Read more
Best Buy is clearing out iPad Airs for up to...
In advance of next week’s probably release of new and updated iPad Airs, Best Buy has 10.9″ M1 WiFi iPad Airs on record-low sale prices for up to $200 off Apple’s MSRP, starting at $399. Sale prices... Read more
Every version of Apple Pencil is on sale toda...
Best Buy has all Apple Pencils on sale today for $79, ranging up to 39% off MSRP for some models. Sale prices for online orders only, in-store prices may vary. Order online and choose free shipping... Read more
Sunday Sale: Apple Studio Display with Standa...
Amazon has the standard-glass Apple Studio Display on sale for $300 off MSRP for a limited time. Shipping is free: – Studio Display (Standard glass): $1299.97 $300 off MSRP For the latest prices and... Read more
Apple is offering significant discounts on 16...
Apple has a full line of 16″ M3 Pro and M3 Max MacBook Pros available, Certified Refurbished, starting at $2119 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free... Read more
Apple HomePods on sale for $30-$50 off MSRP t...
Best Buy is offering a $30-$50 discount on Apple HomePods this weekend on their online store. The HomePod mini is on sale for $69.99, $30 off MSRP, while Best Buy has the full-size HomePod on sale... Read more
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

Jobs Board

Licensed Practical Nurse - Womens Imaging *A...
Licensed Practical Nurse - Womens Imaging Apple Hill - PRN Location: York Hospital, York, PA Schedule: PRN/Per Diem Sign-On Bonus Eligible Remote/Hybrid Regular 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
Operating Room Assistant - *Apple* Hill Sur...
Operating Room Assistant - Apple Hill Surgical Center - Day Location: WellSpan Health, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Read more
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
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.