views:

132

answers:

2

In the hope of fixing a bug of mine from another post i would like to know why apple writes this (for it's Elements example)

UIView *localContainerView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
self.containerView = localContainerView;
[localContainerView release];

instead of the simpler method:

containerView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];

?

+3  A: 

self.containerView = is actually [self setContainerView:], which will usually release any previous value before assigning a new value. When you assign directly, you have to know that the member was not holding a reference to anything, for example because you just released it or checked for a nil value.

[self setContainerView:] can also handle any additional processing.

drawnonward
+2  A: 

Well, it's kind of difficult to answer this one given the 'simpler method' you demonstrate could either result in perfectly optimal code or a rather unfortunate memory leak!

As Drawnonward points out, setting self.containerView is the same as calling [self setContainerView:], and if you're using @synthesize to generate your getters and setters, your setContainerView: method will look something like this:

- (void)setContainerView:(UIView *)view {
    if (containerView != view) {
        [view retain]
        [containerView release];
        containerView = view;
    }
}

As you can see, these setters handle all of the memory management for you, so I figure Apple likes to encourage developers to take advantage of this.

Of course, if you're acutely aware of your pointers and reference counts then there's absolutely nothing wrong with setting containerView directly, as you demonstrated.

EDIT: You can do what you're trying to do in one line of code, while also making use of your setter to simplify memory management, with the following:

self.containerView = [[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
David Foster