我在某处读到,在 UIViewController 中以编程方式创建的视图中,不使用 Interface Builder,-viewDidLoad
不-viewDidUnload
应该使用。这是正确的吗?为什么?我将在哪里发布我保留属性的子视图?还是我不应该为他们使用属性?
编辑:阅读我对 Rob Napier 回答的评论。
我在某处读到,在 UIViewController 中以编程方式创建的视图中,不使用 Interface Builder,-viewDidLoad
不-viewDidUnload
应该使用。这是正确的吗?为什么?我将在哪里发布我保留属性的子视图?还是我不应该为他们使用属性?
编辑:阅读我对 Rob Napier 回答的评论。
在 中创建您的子视图-viewDidLoad
。如果您需要它们的 ivars,则只需分配它们的值。通过将视图作为子视图添加到主视图来保持引用。
然后,当您的视图被卸载时,您应该将您的 ivars 设置为 nil,因为自从您的视图被删除和释放后,该对象已被释放。
所以在你的标题中
@interface MyViewController : UIViewController {
IBOutlet UIView *someSubview; // assigned
}
@property (nonatomic, assign) IBOutlet UIView someSubview;
@end
在你的实施中
@implementation MyViewController
//... some important stuff
- (void)viewDidLoad;
{
[super viewDidLoad];
someSubview = [[UIView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:someSubview]; // retains someSubview
[someSubview release]; // we don't hold it
}
- (void)viewDidUnload;
{
[super viewDidUnload];
someSubview = nil; // set the pointer to nil because someSubview has been released
}
//... more important stuff
@end
如果你希望你也不能在 中释放someSubview
,-viewDidLoad
但是你必须在-viewDidUnload
AND中释放它,-dealloc
因为(如果我没记错的话)-viewDidUnload
之前没有被调用-dealloc
。但如果你不保留,这不是必需的someSubview
。
奇怪的是,没有从 NIB 文件加载的 UIViewController 不会收到有关其视图卸载的通知(因此不会调用其 viewDidUnload 方法),除非您提供 loadView 方法的基本实现,例如:
- (void)loadView {
self.view = [[[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds] autorelease];
[self.view setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];
}
- (void)viewDidLoad {
[super viewDidLoad];
// create views...
}
- (void)viewDidUnload {
// destroy views...
[super viewDidUnload];
}
这只发生在基本 UIViewController 上,例如 UITableViewController 不需要用这个 workaroud 修复。
所以罗布斯是对的。