【发布时间】:2011-04-11 02:43:39
【问题描述】:
我正在创建一个加载屏幕 UIView,它被添加到子视图中,同时从某个 URL 解析一些 XML。返回 XML 后,加载屏幕将从其父视图中移除。
我的问题是我应该如何释放这个对象?
在下面的代码中,您会看到我将removeFromSuperview 发送到 loadingScreen,但除非我释放它,否则我仍然拥有该对象的所有权。但是,如果我发布它,viewdidUnload 和 dealloc 将没有任何内容可以发布。
- (void)loadView {
...
loadingScreen = [[LoadingScreen alloc] initWithFrame: self.view.frame];
[self.view addSubview:loadingScreen]; //retain count = 2
}
-(void)doneParsing {
...
[loadingScreen removeFromSuperview]; //retain count = 1
[loadingScreen release]; //should i release the loading screen here?
}
- (void)viewDidUnload {
[loadingScreen release]; //if viewDidUnload is called AFTER doneParsing, this
//will cause an exception, but the app might crash before
//doneParsing is called, so i need something here
}
- (void)dealloc {
[loadingScreen release]; //if i've already released the object, i can't release here
}
【问题讨论】:
-
其实我想我已经解决了这个问题,方法是在将 loadingScreen 添加为子视图后释放 loadingScreen,然后在 doneParsing 中从父视图中删除 loadingScreen。我没有在 viewDidUnload 或 dealloc 中释放 loadingScreen。
-
这是正确的。把它交给superview,然后释放它。在那之后,这不再是你的责任,你可以忘记它。当superview自己释放时,superview会释放它。
标签: iphone objective-c memory-management uiview dealloc