nevan king
nevan king

Reputation: 113757

Why does this code from iPhone Developer's Cookbook work?

I've been trying out some of the view code from Erica Sadun's book "The iPhone Developer's Cookbook" and found some code I don't understand. Here's the code for a loadView method:

- (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];
}

My question is why does she release contentView, but then use it again in [contentView addSubview:subview]? Has self.view = contentView retained contentView?

Upvotes: 1

Views: 400

Answers (2)

Dave DeLong
Dave DeLong

Reputation: 243156

If you look in the documentation for UIViewController, you'll see that the view property is declared as:

@property(nonatomic, retain) UIView *view;

This means that when you use the setView: method (or use .view on the left hand side of the =), then whatever value you pass in will be retained. So, if you go through the code and look at retain counts, you'll get this:

- (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];

}

I'd say that the really interesting thing is that after releasing contentView, we can still send messages to it, because the object living at the end of contentView's pointer still exists (since it was retained by calling setView:).

Upvotes: 7

Daniel
Daniel

Reputation: 22405

If u declare ur property like so @property(nonatomic,retain) ... TheN yes the property is retained when assigned. that is probably what's going on

Upvotes: 0

Related Questions