Selector for SystemStatusBar::NSStatusItem is unrecognized

419 views Asked by At

I am trying to receive an event when the NSStatusItem is clicked (Action is performed). However, this is what I see in the console (the application does not crash) - unrecognized selector sent to instance

2014-11-14 00:42:29.565 T1[90662:303] -[NSSystemStatusBar somethingHappened]: unrecognized selector sent to instance 0x61000008c990
2014-11-14 00:42:29.573 T1[90662:303] (
    0   CoreFoundation  
. . .

This is the code that I am trying to work with:

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate
{
    var statusBar = NSStatusBar.systemStatusBar();
    var statusBarItem : NSStatusItem! = NSStatusItem();
    override func awakeFromNib()
    {   
        statusBarItem = statusBar.statusItemWithLength(-1)
        statusBarItem.target = self
        statusBarItem.action = Selector("somethingHappened");
        statusBarItem.menu = nil;
    }
    @IBAction func somethingHappened(sender: NSStatusItem)
    {
        println("Hello from StatusItem");
    }
}

In order to understand what is going wrong with this, I've translated a couple of exactly similar Objective-C tutorials to Swift, but there seems to be something that I am missing but not able to figure out.

1

There are 1 answers

1
Martin R On BEST ANSWER
statusBarItem.target = NSStatusBar.systemStatusBar()
statusBarItem.action = Selector("somethingHappened")

should be

statusBarItem.target = self
statusBarItem.action = Selector("somethingHappened:");

The action target is the AppDelegate instance, and the selector "somethingHappened:" (with the colon) because the method takes one argument.

For Swift 2.2/Xcode 7.3 it is

statusBarItem.action = #selector(somethingHappened(_:));