代码之家  ›  专栏  ›  技术社区  ›  rtemp

目标C使用UITableViewCell释放对象时发生泄漏

  •  1
  • rtemp  · 技术社区  · 15 年前

    我正在TableView中运行以下代码:CellForRowatindexPath:

    File *file = [[File alloc] init];
    file = [self.fileList objectAtIndex:row];
    UIImage* theImage = file.fileIconImage;
    
    cell.imageView.image = theImage;
    cell.textLabel.text = file.fileName;
    cell.detailTextLabel.text = file.fileModificationDate;
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    return cell;
    

    我运行泄漏工具,发现文件对象正在泄漏,因为我没有释放它。因此,我在返回我认为安全的单元之前添加了释放(如下所示):

    File *file = [[File alloc] init];
    file = [self.fileList objectAtIndex:row];
    
    UIImage* theImage = file.fileIconImage;
    
    cell.imageView.image = theImage;
    cell.textLabel.text = file.fileName;
    cell.detailTextLabel.text = file.fileModificationDate;
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    [file release];
    
    return cell;
    

    现在,当我运行应用程序时,它崩溃了。UITableViewCells是否仍引用文件对象?在这里使用什么方法来确保我没有泄漏内存?

    2 回复  |  直到 15 年前
        1
  •  6
  •   Rüdiger Hanke shraddha hattimare    15 年前
    File *file = [[File alloc] init];
    file = [self.fileList objectAtIndex:row];
    

    好吧,这里你先分配一个新的 File 然后丢弃指针,显然从数组中获取另一个现有对象。如果你打电话的话,你就会把它释放出来。 release 后来。你打电话的那个 释放 最后不是你分配的那个。指向新分配的指针丢失,因此泄漏。

    可能是因为 self.fileList 其后包含指向已销毁对象的指针。

    也许你只是想写

    File *file = [self.fileList objectAtIndex:row];
    
        2
  •  1
  •   h4xxr    15 年前

    是的,在你发布的时候,手机仍然在引用它,所以应用程序崩溃了。

    申报时需要使用autorelease,如下所示:

    File *file = [[[File alloc] init] autorelease];
    

    那么,不要调用[文件发布]部分。一旦它不再被引用(即当您停止使用单元时),它将在下一个运行循环开始时自动释放。