Open NSWindowController from NSMenu

I am using NSMenu in an agent application (without an icon in the dock). When a button from this menu is pressed, I want to show a generic NSWindowController.

My menu action:

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

But the window simply โ€œblinksโ€ on the screen (it is displayed and disappears very quickly).

Any solution?

+4
source share
2 answers

The reason a window appears for a second of a second and then disappears is related to ARC and the way you are going to instantiate the window controller:

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

In ARC, an instance of myWindow will be valid for the scope in which it is defined. In other words, after reaching and running the last line [[myWindow window] makeMainWindow]; the window controller will be freed and freed, and as a result, its window will be removed from the screen.

Generally speaking, for the objects or objects that you create that you want to stick to, you must define them as an instance variable with the strong property.

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

 @class MyWindowController; @interface MDAppController : NSObject @property (nonatomic, strong) MyWindowController *windowController; @end 

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

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

Use this:

 [[myWindow window] makeKeyAndOrderFront:self]; 
0
source

Source: https://habr.com/ru/post/1446775/


All Articles