Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSwindow disappear

I want to add a NSWindow the simple code is :

NSWindow* myWindow;
myWindow = [[NSWindow alloc] initWithContentRect:NSMakeRect(100,100,300,300)
                                       styleMask:NSTitledWindowMask
                                         backing:NSBackingStoreBuffered
                                           defer:NO];
[myWindow makeKeyAndOrderFront:nil];

And the window appears for a second then disappears. What's wrong?

  • Xcode 4.5.2
  • MacBookPro i5 10.8.2

Thanks for your answer.

like image 240
Simon V. Avatar asked Dec 31 '12 11:12

Simon V.


1 Answers

You are not retaining the window.

Define NSWindow* myWindow; in .h as a property.


In .h

@property (strong)NSWindow* myWindow;

In .m

- (IBAction)button:(id)sender {

   if (self.myWindow==nil){
      self.myWindow= [[NSWindow alloc] initWithContentRect:NSMakeRect(100,100,300,300)
                                               styleMask:NSTitledWindowMask
                                                 backing:NSBackingStoreBuffered
                                                   defer:NO];
   }

   [self.myWindow makeKeyAndOrderFront:NSApp];

}

EDIT:

If you want multiple windows to open from same button. Create an array

In .h

@property(strong) NSMutableArray *myWindowArray;

In .m

- (IBAction)button:(id)sender {
    self.myWindow= [[NSWindow alloc] initWithContentRect:NSMakeRect(100,100,300,300)
                                                   styleMask:NSTitledWindowMask
                                                     backing:NSBackingStoreBuffered
                                                       defer:NO];


    [self.myWindowArray addObject:self.myWindow];

    for (NSWindow *win in self.myWindowArray) {
        [win makeKeyAndOrderFront:NSApp];

    }
}

EDIT 2:

Find the application here.

like image 78
Anoop Vaidya Avatar answered Oct 02 '22 01:10

Anoop Vaidya