记忆管理问题

时间:2010-08-26 04:44:06

标签: objective-c cocoa memory-management

我有一个带有IBAction的按钮,它显示另一个窗口:

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

}

我担心这里的内存管理。我在这个IBAction中分配了一个对象,但是没有释放它。但是我该怎么做呢?如果我在显示后释放了这个对象,窗口将立即关闭。

2 个答案:

答案 0 :(得分:2)

视图存储在一个实例变量中,您可以在类中的任何位置访问它。在解除视图的代码中释放它。

答案 1 :(得分: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。

而且你应该重命名你的实例变量,名称应该反映它是什么。并且视图不是窗口控制器。

相关问题