【问题标题】:Objective C Leaks when releasing objects with UITableViewCell使用 UITableViewCell 释放对象时,Objective C 泄漏
【发布时间】:2010-11-22 09:50:19
【问题描述】:

我在 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 = [[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 是否仍在引用文件对象?在这里使用什么方法来确保我没有泄漏内存?

【问题讨论】:

    标签: iphone objective-c xcode memory-leaks


    【解决方案1】:

    是的,在您释放它时,该单元格仍在引用它,因此应用程序崩溃了。

    声明时需要使用autorelease,如下:

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

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

    【讨论】:

      【解决方案2】:
      File *file = [[File alloc] init];
      file = [self.fileList objectAtIndex:row];
      

      好吧,在这里您首先分配一个新的File,然后您丢弃指针并显然从数组中获取另一个现有对象。如果您稍后致电release,那就是您发布的那个。最后你调用release的那个不是你分配的那个。指向新分配的指针丢失并因此泄漏。

      它可能会崩溃,因为self.fileList 包含一个指向此后已销毁对象的指针。

      也许你只想写

      File *file = [self.fileList objectAtIndex:row];
      

      【讨论】:

      • 公平,没有看过那一点,只建议使用 alloc/init 自动释放...但你是对的,他不需要分配/初始化文件对象全部!
      猜你喜欢
      • 2011-10-16
      • 2010-12-22
      • 2021-05-21
      • 1970-01-01
      • 1970-01-01
      • 2011-03-09
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      相关资源
      最近更新 更多