在 iOS 4.x 或更低版本中,这是释放保留在 viewDidLoad
中的 View 的正确(最佳?)方式吗?还有什么要考虑的吗?
- (void) viewDidUnload
{
[super viewDidUnload];
[self releaseViews];
}
- (void) dealloc {
[self releaseViews];
[super dealloc];
}
#define SAFE_RELEASE(a) [a release]; a = nil;
- (void) releaseViews {
SAFE_RELEASE(myView1);
SAFE_RELEASE(myView2);
SAFE_RELEASE(myView3);
}
最佳答案
-dealloc
是正确的,-viewDidUnload
将起作用,但通常保留的 View 仅在 -viewDidUnload
中被清空,并且不会被释放。这似乎也是 Apple 的做法,当您通过 Assistant 编辑器创建自动生成的 IBOutlet 时,他们将其融入 Xcode。
对于自动生成的 IBOutlets,自动生成的 -viewDidUnload
看起来像这样:
- (void)viewDidUnload {
[self myView1:nil];
[self myView2:nil];
[self myView3:nil];
[super viewDidUnload];
}
此外,来自 Apple docs在 -viewDidUnload
上:
The preferred way to relinquish ownership of any object (including those in outlets) is to use the corresponding accessor method to set the value of the object to nil. However, if you do not have an accessor method for a given object, you may have to release the object explicitly
所以,你去吧。如果你的 outlet 有一个与之关联的属性(它们都应该再这样了),那么在 -viewDidUnload
中将它置零——但不要释放它。当您考虑合成访问器中实际发生的事情时,这是有道理的;代码看起来像这样:
- (void) setMyView1 : (UIView *) view {
if (myView1) // the associated IVAR is already set
[myView1 release];
myView1 = [view retain];
}
如您所见,将合成属性设置为 nil 会隐式释放保留的对象。
也来自关于 -dealloc
的文档:
If you implement this method but are building your application for iOS 2.x, your dealloc method should release each object but should also set the reference to that object to nil before calling super.
除非你支持 iOS2.x,否则不需要在 dealloc 中将对象设置为 nil。
因此,总结 Apple 关于 -viewDidUnload
和 -dealloc
的文档:
- 在
-viewDidUnload
中,没有属性(包括 IBOutlet 属性),但不要释放它们 - 在
-dealloc
中释放属性,但不要将它们置零(除非为 2.x 构建)。
关于iphone - 发布保留 View 的最佳实践?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7057887/