UITableViewCell背景消失了吗?

时间:2013-09-06 22:53:55

标签: iphone ios objective-c uitableview

我的应用程序中的UITableViewController从json数据源中提取数据。我还使用CG创建了一个自定义UITableViewCell背景。发生了一个非常有趣的错误,我不明白为什么。我将引导您了解发生的事情以及我如何重新创建它:

点按进入表格视图。 在没有滚动表的情况下,我立即点击视图中的项目。 点击该项目后,按后退按钮返回到表格视图。 如果我然后向下滚动第一个单元格从屏幕外显示将没有我的自定义背景。它只是一个单元格的默认值。然后,如果我继续向下滚动每10个单元格将有相同的问题。

此错误仅发生在此确切过程中。如果我在点击某个项目之前完全滚动表格视图,则不会发生这种情况。

以下是tableview控制器的相关代码:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Will remove all of the used codes from the table if setting is enabled
    if (self.shouldHideCodes) {
        NSMutableArray *tempArray = [self.jsonCodeData mutableCopy];
        [tempArray removeObjectsInArray:[self.usedCodes usedCodes]];
        self.jsonCodeData = tempArray;
    }

    return [self.jsonCodeData count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell;

    if (self.jsonCodeData) {
        cell = [tableView dequeueReusableCellWithIdentifier:@"code cell"];

        if ([cell isKindOfClass:[CodeCellTVC class]]) {
            CodeCellTVC *tvcCell = (CodeCellTVC *)cell;

            if (![tvcCell.backgroundView isKindOfClass:[CustomCellBackground class]]) {
                tvcCell.backgroundView = [[CustomCellBackground alloc] init];
            }

            NSDictionary *codeDict = [self.jsonCodeData objectAtIndex:indexPath.row];


            // Retrieve code string from dictionary
            NSString *codeText = [NSString stringWithFormat:@"%@", [codeDict objectForKey:@"code"]];

            tvcCell.codeTableLabel.text = codeText;

        }
    }

    return cell;
}

令我困惑的是它的反应。当bug发生时,每10个单元都有问题,而不是每个单元。我没有处理tableviewcell本身的这些方法之外的任何东西。

1 个答案:

答案 0 :(得分:0)

我理解你的问题,你在初始化单元格时做错了,每当你初始化单元格时,每次内存都会分配给那个单元格,就会产生内存问题。 编辑下面的代码,它会对你有用。

    cell = [tableView dequeueReusableCellWithIdentifier:@"code cell"];

    if(cell == nil)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"code cell"];
    }
相关问题