iphone - 发布保留 View 的最佳实践?

标签 iphone ios release dealloc viewdidunload

在 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/

相关文章:

iphone - "Apple Mach-O linker command failed with exit code 1"

ios - Storyboard生成的 UIScrollView 不滚动

ios - UITabBarController 选择标签错误(?)

ios - 在 TabBarController 上切换选项卡时关闭所有详细 View

gradle - Gradle发行插件:如何将版本保留在文本文件中(而不在属性文件中)?

iphone - NSString到NSArray

ios - 在关闭模态视图 Controller 的动画时访问 presentingViewController

iphone - navigationItem.backBarButtonItem 不工作?为什么以前的菜单仍然显示为按钮?

android - zipalign验证失败如何解决?

c# - 编译并运行一个包含声音文件的完成项目