何时发布从超级视图中移除的UIView
问题描述:
我正在创建一个加载屏幕UIView,它被添加到子视图中,而某些XML从某个URL被解析。一旦XML返回,加载屏幕将从其超级视图中移除。何时发布从超级视图中移除的UIView
我的问题是我该如何释放这个对象?
在下面的代码中,您会看到我将removeFromSuperview
发送到加载屏幕,但我仍然拥有此对象的所有权,除非我将其释放。但是,如果我释放它,那么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 release];
loadingScreen = nil;
[nil release]不会发生任何事情。
其实我认为我已经通过在作为子视图添加之后释放loadingScreen来解决此问题,然后从doneParsing中的superview中移除loadingScreen。我没有在viewDidUnload或dealloc中释放loadingScreen。 – dianovich 2010-09-11 14:13:16
这是正确的。把它给予超级视图,然后释放它。之后,这不再是你的责任,你可以忘掉它。当超级视图被释放时,超级视图将释放它。 – 2010-09-11 15:14:03