我一直在尝试一些来自Erica Sadun的书“iPhone Developer's Cookbook”的视图代码,并发现了一些我不明白的代码。下面是一个的loadView方法的代码:为什么iPhone Developer's Cookbook的这段代码有效?
- (void)loadView
{
// Create the main view
UIView *contentView = [[UIView alloc] initWithFrame:
[[UIScreen mainScreen] applicationFrame]];
contentView.backgroundColor = [UIColor whiteColor];
self.view = contentView;
[contentView release];
// Get the view bounds as our starting point
CGRect apprect = [contentView bounds];
// Add each inset subview
UIView *subview = [[UIView alloc]
initWithFrame:CGRectInset(apprect, 32.0f, 32.0f)];
subview.backgroundColor = [UIColor lightGrayColor];
[contentView addSubview:subview];
[subview release];
}
我的问题是,为什么她释放内容查看,但随后在[contentView addSubview:subview]
再次使用它?有self.view = contentView
保留contentView?
这看起来不对。 'contentView'不会在方法结束之前被释放,所以这可能不会导致任何问题,但我无法想象为什么你会故意用这种方式构建它。 – kubi 2009-08-09 00:33:51
不是。对self.view的赋值保留了contentView,所以在创建对象时最近可以得到它。这是故意构建的,因为(在Cocoa范例中)视图控制器保留视图是有意义的。 – 2009-08-09 15:40:31