Frage

I'm new to Mac OSX development. I wanna build a global menu item which allows to enter a text and after pressing return, it should jump to a webpage. Nothing special.

What confuse me is the following part of my simple code:

I create my global menu item and its NSMenu dropdown in the (void)applicationDidFinishLaunching:(NSNotification *)aNotification method of the AppDelegate.m.

If I say, that the NSStatusItem is a privat local method variable, the status item will not show up in the global menu bar after running the application.

If I declare the variable as private class global (above the method), the icon shows up as wished.

Thanks for your help.

The complete source code:

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    // Use a NSMenu as dropdown component
    NSMenu* dropdown = [NSMenu new];

    // Disable auto enabled items
    [dropdown setAutoenablesItems:NO];

    // Add custom view menu item

    // 1. Add a empty item to menu
    NSMenuItem* item = [NSMenuItem new];
    [dropdown addItem: item];

    // 2. Create a new custom view with a placeholder rectangle
    NSView* view = [[NSView new] initWithFrame: NSMakeRect(0,0,200,20)];
    item.view = view;

    // 3. Add a text field to the custom view
    NSTextField* textField = [[NSTextField alloc] initWithFrame: NSMakeRect(5,0,190,20)];
    [view addSubview: textField];

    // Add seperator
    [dropdown addItem:[NSMenuItem separatorItem]];

    // Add quit button
    NSMenuItem* menuItem = [dropdown addItemWithTitle:@"Quit"
                                               action:@selector(terminate:)
                                        keyEquivalent:@"q"];

    // Add cmd-key as required keyboardshortcut starting point
    [menuItem setKeyEquivalentModifierMask:NSCommandKeyMask];

    // Get a statusbar item
    NSStatusItem* statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:NSVariableStatusItemLength];

    // Set icon
    [statusItem setImage:[NSImage imageNamed:@"icon.png"]];

    // Set tooltip
    [statusItem setToolTip:@"Jump to an issue."];

    // Enable highlighting on click.
    // If left mouse button is pressed, paint the background blue.
    // Default behabior for status item according zo UI guidlines is YES,
    // but the default value of a status item would be NO.
    [statusItem setHighlightMode:YES];

    // Set the dropdown as visible menu
    [statusItem setMenu:dropdown];
}
War es hilfreich?

Lösung

Because if you only declare the object inside the method and don't keep a reference to it elsewhere it will be scoped to the method. When the method finishes execution your object will be released and go away. If you want it to live as long as the app runs, you would want to assign it to a property of the app delegate or another object that is going to live as long as the app.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top