user14492
user14492

Reputation: 2234

NSStatusItem not showing image and title

I am trying to make a Status Bar Item, the ones like the battery or time machine indicator on top right. The code I have is below

- (void)activateStatusBarItem:(id)object{
NSStatusBar *systemBar = [NSStatusBar systemStatusBar];

NSStatusItem *theItem = [systemBar statusItemWithLength:NSVariableStatusItemLength];

NSImage *statusBarIcon = [NSImage imageNamed:@"icon-sleep.png"];
statusBarIcon.size = CGSizeMake(NSSquareStatusItemLength, NSSquareStatusItemLength);

[theItem setImage:statusBarIcon];
[theItem setTitle:@"abc"];
[theItem setTarget:self];
[theItem setAction:@selector(showHUD:)];
}

This method is called when the app launches. However, I don't see theItem on the menu. It did work once which the same code without the image.

Also when I look into Apple's and there the methods: - setTitle: - setImage: - setTarget: - setAction: all say that they are available and depreciated at the same time, look at the image below. Is there any other way, I can do this. I want a window/panel to show up when the Item is clicked, possibly attached to the bar.

enter image description here

Upvotes: 0

Views: 1471

Answers (1)

Ken Thomases
Ken Thomases

Reputation: 90531

You are setting the image size to nonsensical values. NSSquareStatusItemLength is -2. It's a sentinel value, not an actual length.

You would need to use systemBar.thickness to determine the actual size that would be used for a square status item.

Regarding the deprecated methods, in 10.10, NSStatusItem has a new button property. This should be used instead of the now-deprecated view property (which you weren't using). All of the other deprecated properties are now just cover methods that call through to the corresponding methods on the button. It is safe to use those cover methods and they should still work.

You are not keeping a strong reference to the status item. It's just stored in a local variable. If you're using ARC, that means that it is released at the end of your -activateStatusBarItem: method, which removes it from the status bar. So, you're creating it and removing it in rapid succession. You should keep a strong reference, probably in an instance variable. The requirement to keep a strong reference is documented for +[NSStatusBar statusItemWithLength:]:

The receiver does not retain a reference to the status item, so you need to retain it. Otherwise, the object is removed from the status bar when it is deallocated.

Upvotes: 2

Related Questions