views:

41

answers:

1

I have a UIViewController that contains a UIView. Between every time the viewcontroller is displyaed, the UIView has to be cleared and the content reloaded. The problem is that the old content still appears in the UIView.

Load data before controller becomes visible:

- (void)viewWillAppear:(BOOL)animated
{
    contentView = [[ContentView alloc] initWithFrame:CGRectMake(10, 10, 100, 100)];
    contentView.userInteractionEnabled = NO;
    [self.view addSubview:contentView];

    if([self loadContentData] == NO) {
        [contentView release];
        return NO;
    }
    return YES;
}

Remove content after controller is hidden:

- (void)viewDidDisappear:(BOOL)animated
{
    [contentView removeFromSuperview];
    [contentView release];
}

Why is this cleanup not sufficient?

A: 

Try:

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [contentView removeFromSuperView];  //releases contentView
}

You must call super's method when overriding this method.

Additionally, contentView appears to be over-released in the code you've posted which makes me believe you are retaining it possibly somewhere in your real code. If this is the case, you may have over-retained contentView, which will prevent it from being released and cleaned up from your view hierarchy.

I would suggest you explore something along these lines:

- (void)viewWillAppear:(BOOL)animated
{
    contentView = [[[ContentView alloc] initWithFrame:CGRectMake(10, 10, 100, 100)] autorelease];
    contentView.userInteractionEnabled = NO;
    [self.view addSubview:contentView];

    if([self loadContentData] == NO) {
        //[contentView release];  //ContentView is now autoreleased and will be dropped when the method exits.
        return NO; //this probably has a compiler warning, since it is a (void) method
    }
    return YES; //this probably has a compiler warning, since it is a (void) method
}
Chip Coons
removeFromSuperView releases the superview retain of the view. Since the view was not released before it had a retain count of +1 when created, +2 when assigned to the super view, +1 when the super view releases it. OP still has to release contentView or else suffer from a memory leak.
Brandon Bodnár
I agree, that's why I questioned what OP's real code looks like. If he executes the if statement, he is over released. The fact that he is returning values for a (void) method lead me to believe there is more in his real code than what was posted for setting the view initially. I'll edit my answer to be more explicit on this.
Chip Coons