【发布时间】:2010-06-17 17:20:01
【问题描述】:
在我的应用程序工作流程的各个阶段,我都需要展示一个视图。该视图非常占用内存,因此我希望在用户丢弃它时将其释放。于是,我写了如下代码:
- (MyView *)myView {
if (myView != nil)
return myView;
myView = [[UIView alloc] initWithFrame:CGRectZero]; // allocate memory if necessary.
// further init here
return myView;
}
- (void)discardView {
[myView discard]; // the discard methods puts the view offscreen.
[myView release]; // free memory!
}
- (void)showView {
view = [self myView];
// more code that puts the view onscreen.
}
不幸的是,这种方法只能在第一次使用。将视图显示在屏幕上的后续请求会导致 "message sent to deallocated instance" 错误。显然,释放的实例与 nil 不同。我想在[myView release] 后面加一行,写成myView = nil。但是,这可能会导致错误(在该行之后对 myView 的任何调用都可能会产生错误)。
那么,我该如何解决这个问题呢?
【问题讨论】:
-
如果您在发布 myView 后调用它,您希望产生错误。
标签: iphone cocoa cocoa-touch memory-management null