2012-12-31 33 views
5

我想補充一個NSWindow簡單的代碼是:NSwindow消失

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

,出現窗口第二個,然後消失。 有什麼問題?

  • 的Xcode 4.5.2
  • 酷睿i5的MacBookPro 10.8.2

謝謝您的回答。

回答

10

您不保留窗口。

定義爲NSWindow* myWindow;作爲一個屬性.h。


在.H

@property (strong)NSWindow* myWindow; 

在.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]; 

} 

編輯:

如果需要多個窗口,從同一按鈕打開。建立一個數組

在.H

@property(strong) NSMutableArray *myWindowArray; 

在.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]; 

    } 
} 

編輯2:

查找application here

+0

使這個「'self.myWindow'」和答案會好得多。此外,在創建新窗口之前,您可能需要檢查是否已經有一個窗口分配給「self.myWindow」。 –

+0

當然...更新:) –

+0

謝謝。完美的作品。 –