我在 xcode 中进行分析时发现了内存泄漏问题。这个问题很简单,但我不明白如何解决它:
考虑一个带有 2 个按钮和一个 tableview 的 uiviewcontroller。 Button1=从服务器加载 JSON 数据并将单元格添加到 tableview,然后 [tableview reloadData]
button2=从另一台服务器加载 JSON 数据并将单元格添加到表格 View ,然后重新加载。
好的,问题出在:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)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 中泄漏,所以我认为我需要在重新加载之前“清除”(释放)所有单元格数据?
谢谢
最佳答案
您应该在 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/