2010-08-26 110 views
0

我有IBAction爲一個按鈕,它顯示的另一個窗口:內存管理問題

-(IBAction)someButtonClick:(id)sender 
{ 
    anotherView = [[NSWindowController alloc] initWithWindowNibName:@"AnotherWindow"]; 
    [anotherView showWindow:self]; 

} 

我擔心內存管理在這裏。我在這個IBAction中分配一個對象並且不會釋放它。但我該怎麼做呢?如果我在顯示後發佈此對象,窗口將立即關閉。

回答

1

由於anotherView是一個實例變量,您可以在dealloc方法中釋放它。但是,您仍然有內存泄漏,因爲每次單擊按鈕時都會創建一個窗口控制器的新實例,但只有最後一個可以被釋放。你真的應該使用訪問器來做到這一點。這裏是我的建議:

- (NSWindowController *) anotherView; 
{ 
    if (nil == anotherView) { 
     anotherView = [[NSWindowController alloc] initWithWindowNibName:@"AnotherWindow"]; 
    } 
    return anotherView; 
} 

- (void) setAnotherView: (NSWindowController *) newAnotherView; 
{ 
    if (newAnotherView != anotherView) { 
     [anotherView release]; 
     anotherView = [newAnotherView retain]; 
    } 
} 


- (void) dealloc; 
{ 
    [self setAnotherView: nil]; 
    [super dealloc]; 
} 


- (IBAction) someButtonClick: (id) sender; 
{ 
    [[self anotherView] showWindow: self]; 
} 

如果您使用Objective-C 2.0屬性,則不必編寫setter。

而且你應該重命名你的實例變量,名稱應該反映它是什麼。而一個視圖不是一個窗口控制器。

+1

更好的是,只有在窗口控制器尚未創建之前創建窗口控制器。如果有,只需發送一個已經有'showWindow:'消息的消息。 – 2010-08-26 07:11:23

+0

這正是我的代碼所做的。 getter -anotherView創建窗口控制器,如果沒有的話。如果已經有一個它只是返回。所以'-someButtonClick:'總是得到同一個對象。 – Sven 2010-08-26 07:30:17

2

該視圖存儲在一個實例變量中,並且您可以在類中的任何位置訪問該視圖。在解除視圖的代碼中釋放它。