我有一个带有IBAction的按钮,它显示另一个窗口:
-(IBAction)someButtonClick:(id)sender
{
anotherView = [[NSWindowController alloc] initWithWindowNibName:@"AnotherWindow"];
[anotherView showWindow:self];
}我担心这里的内存管理。我在这个IBAction中分配了一个对象,但没有释放它。但是我该怎么做呢?如果我在显示后释放此对象,窗口将立即关闭。
发布于 2010-08-26 14:52:12
因为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-C2.0属性,则不必编写setter。
你也应该重命名你的实例变量,这个名称应该反映它是什么。并且View不是Window Controller。
发布于 2010-08-26 12:55:03
视图存储在实例变量中,您可以在类中的任何位置访问它。在关闭视图的代码中释放它。
https://stackoverflow.com/questions/3572112
复制相似问题