对于 View Controller ,必须释放您在 Interface Builder 中设置的任何导出 并在 viewDidUnload 中设置为 nil,并且还必须在 dealloc 中释放。
(参见:When should I release objects in viewDidUnload rather than in dealloc?)
One of the most important reasons for implementing [viewDidUnload] is that UIViewController subclasses commonly also contain owning references to various subviews in the view hierarchy. These properties could have been set through IBOutlets when loading from a nib, or programmatically inside loadView [emphasis added], for instance.
我的问题是,我们是否真的需要为在 loadView(没有 Interface Builder)中以编程方式创建的 View 层次结构中的 subview 实现 viewDidUnload?
最佳答案
这取决于您创建它们的方式以及您是否需要在其他地方引用它们。
例如:
- (void)loadView
{
[super loadView];
UIButton *someButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
someButton.frame = CGRectMake(0, 0, 50, 50);
[self.view addSubview: someButton];
}
在上述情况下,您不需要实现 viewDidUnload,因为 someButton 在 loadView 中自动释放。
另一个例子:
- (void)loadView
{
[super loadView];
self.someButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
someButton.frame = CGRectMake(0, 0, 50, 50);
[self.view addSubview: someButton];
}
在这个例子中,你会想要使用 viewDidUnload,因为你有另一个对 someButton 的引用。您希望 viewDidUnload 释放该按钮并重置引用,这样您就不会不当使用它并释放内存。在这种情况下,您还需要在 dealloc 方法中释放按钮,以防永远不会调用 viewDidUnload。
关于iphone - 以编程方式创建的 subview 和 viewDidUnload,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6442912/