swiftmacosnsstatusbar

NSStatusBar + Swift: title shows and immediately disappear


I want make status bar for macOS, but after I run application title shows and immediately disappears

func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Insert code here to initialize your application
        let statusItem = NSStatusBar.system().statusItem(withLength: NSVariableStatusItemLength)
        statusItem.title = "Hello"

    }

I think something wrong with references, but don't know how to fix this problem.


Solution

  • Indeed you need a strong reference to the status item

    var statusItem : NSStatusItem!
    
    func applicationDidFinishLaunching(_ aNotification: Notification) {
            // Insert code here to initialize your application
            statusItem = NSStatusBar.system().statusItem(withLength: NSVariableStatusItemLength)
            statusItem.title = "Hello"
    
    }
    

    However I recommend to use a closure to initialize the status item

    let statusItem : NSStatusItem = {
        let item =  NSStatusBar.system().statusItem(withLength: NSVariableStatusItemLength)
        item.title = "Hello"
        return item
    }()