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

rte*_*emp 1 iphone xcode memory-leaks objective-c

我在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;
Run Code Online (Sandbox Code Playgroud)

我运行泄漏工具,发现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;
Run Code Online (Sandbox Code Playgroud)

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

Rüd*_*nke 6

File *file = [[File alloc] init];
file = [self.fileList objectAtIndex:row];
Run Code Online (Sandbox Code Playgroud)

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

可能它崩溃了,因为self.fileList此后包含指向已经被破坏的对象的指针.

也许你打算写一下

File *file = [self.fileList objectAtIndex:row];
Run Code Online (Sandbox Code Playgroud)