Pregunta

I'm with a NSMenu in an agent application (without the icon in the dock). When a button from this menu is tapped, I want to show a generic NSWindowController.

My menu button action:

- (IBAction)menuButtonTapped:(id)sender {    
    MyWindowController *myWindow = [[MyWindowController alloc] initWithWindowNibName:@"MyWindowController"];

    [myWindow showWindow:nil];
    [[myWindow window] makeMainWindow];
}

But the window just "flashes" in the screen (it shows and disappears really fast).

Any solution?

¿Fue útil?

Solución

The reason the window is showing up for a split second and then disappearing has to do with ARC and how you go about creating the instance of the window controller:

- (IBAction)menuButtonTapped:(id)sender {    
    MyWindowController *myWindow = [[MyWindowController alloc]
                    initWithWindowNibName:@"MyWindowController"];
    [myWindow showWindow:nil];
    [[myWindow window] makeMainWindow];
}

Under ARC, the myWindow instance will be valid for the scope where it is defined. In other words, after the last [[myWindow window] makeMainWindow]; line is reached and run, the window controller will be released and deallocated, and as a result, its window will be removed from the screen.

Generally speaking, for items or objects you create that you want to "stick around", you should define them as an instance variable with a strong property.

For example, your .h would look something like this:

@class MyWindowController;

@interface MDAppController : NSObject

@property (nonatomic, strong) MyWindowController *windowController;

@end

And the revised menuButtonTapped: method would look something like this:

- (IBAction)menuButtonTapped:(id)sender {
    if (self.windowController == nil) {
         self.windowController = [[MyWindowController alloc]
            initWithWindowNibName:@"MyWindowController"];
    }
    [self.windowController showWindow:nil];
}

Otros consejos

Use this:

[[myWindow window] makeKeyAndOrderFront:self];
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top