OGeek|极客世界-中国程序员成长平台

标题: iphone - 释放tableview ios iphone中的所有单元格 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 16:05
标题: iphone - 释放tableview ios iphone中的所有单元格

我在 xcode 中通过分析发现了内存泄漏问题。这个问题很简单,但我不明白如何解决它:

考虑一个带有 2 个按钮和一个 tableview 的 uiviewcontroller。 button1=从服务器加载 JSON 数据并将单元格添加到 tableview 然后 [tableview reloadData]

button2=从另一个服务器加载 JSON 数据并将单元格添加到 tableview 然后重新加载。

好的,问题出在:

- (UITableViewCell *)tableViewUITableView *)tableView cellForRowAtIndexPathNSIndexPath *)indexPath
{
....
.....
NSURL *url = [NSURL URLWithString:stringpath];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img;
if(!data) img=[UIImage imageNamed"small.jpg"];
else img= [[UIImage alloc] initWithData:data];
cell.imageView.image = img;

好的,如果我每次切换时都用 2 个按钮开始切换,我会从 UIImage 泄漏,所以我认为我需要在重新加载之前“清除”(释放)所有单元格数据?

谢谢



Best Answer-推荐答案


您应该在 cell.imageView.image 中设置后释放 img 对象。我更喜欢 autorelease 在同一行,因为它让我更容易跟踪。

UIImage *img;
if(!data) img=[UIImage imageNamed"small.jpg"];
else img= [[[UIImage alloc] initWithData:data] autorelease];
cell.imageView.image = img;

正如另一个答案中提到的,您可以通过不使用 initWithData 调用,而是使用 imageWithData 来避免痛苦。

细胞会自己照顾自己。

关于iphone - 释放tableview ios iphone中的所有单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5395558/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4