为什么iPhone Developer's Cookbook中的代码有效?

nev*_*ing 1 iphone cocoa-touch objective-c

我一直在尝试从Erica Sadun的书"The iPhone Developer's Cookbook"中查看一些视图代码,并找到了一些我不理解的代码.这是loadView方法的代码:

- (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];
}
Run Code Online (Sandbox Code Playgroud)

我的问题是她为什么发布contentView,然后再次使用它[contentView addSubview:subview]?一直self.view = contentView保留内容查看?

Dav*_*ong 7

如果您查看UIViewController的文档,您将看到view属性声明为:

@property(nonatomic, retain) UIView *view;

这意味着当您使用setView:方法(或在=的左侧使用.view)时,您传入的任何值都将被保留.所以,如果你查看代码并查看保留计数,你会得到这个:

- (void)loadView {
    // Create the main view
    UIView *contentView = [[UIView alloc] initWithFrame: 
            [[UIScreen mainScreen] applicationFrame]];  //retain count +1
    contentView.backgroundColor = [UIColor whiteColor];  //retain count +1
    self.view = contentView;  //retain count +2
    [contentView release];  //retain count +1

    // 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];
Run Code Online (Sandbox Code Playgroud)

}

我要说的是,真正有趣的是,在发布contentView之后,我们仍然可以向它发送消息,因为生活在contentView指针末尾的对象仍然存在(因为它是通过调用setView :)保留的.