删除并重新插入UIView到UIViewController

时间:2010-02-25 12:49:34

标签: cocoa-touch iphone-sdk-3.0

我有一个包含UIView的UIViewController。 在每次调度viewcontroller时,必须清除UIView并重新加载内容。 问题是旧内容仍然出现在UIView中。

在控制器变为可见之前加载数据:

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

隐藏控制器后删除内容:

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

为什么这次清理不够?

1 个答案:

答案 0 :(得分:0)

尝试:

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

重写此方法时,必须调用super的方法。

此外,contentView似乎在您发布的代码中过度发布,这让我相信您可能会将其保留在您的实际代码中。如果是这种情况,您可能会过度保留contentView,这将阻止它从视图层次结构中释放和清除。

我建议你沿着这些方向探讨一些事情:

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