2011-03-22 45 views
2

我有mem泄漏问题与xcode分析发现。这个问题很容易,但我不明白如何解决它:发布桌面视图中的所有单元格iphone

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

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

确定问题出在:

- (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的泄漏,所以我想我需要“清洗”(释放)的所有单元格重新加载之前的数据?

THX

回答

2

你应该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

细胞会照顾好自己。

1

问题不在于释放img,PLZ使用下面

if (!data) 
{ 
    img = [UIImage imageNamed:@"small.jpg"]; 
    cell.imageView.image = img; 
} 
else 
{ 
    img = [[UIImage alloc] initWithData:data]; 
    cell.imageView.image = img; 
    [img release]; 
} 
+0

真的thx现在没有泄漏给我:) – 2011-03-22 17:56:58

1

我将取代这一行:

else img= [[UIImage alloc] initWithData:data]; 

有:

else img= [UIImage imageWithData:data]; 
0

你不必分配UIImage的内存。你可以执行上面的实现,如下:

NSData * data = [NSData dataWithContentsOfURL:url];
cell.imageView.image = [UIImage imageWithData:data];

试试这个。

+0

Thx Stone ..我来自c/C++,对我来说,更容易思考堆栈和堆。如果您按堆栈分配,则在切换上下文时堆栈将被清除,并且在每次新建需要删除时堆栈都将被清除。目前ios中的内存管理仍有点混乱。我从苹果公司获得了内存管理,但规则“如果你分配你的版本”并不总是如此。也许有一天我会停下来像这样失败。 Thx再次。 – 2011-03-22 19:25:39

+0

经过一些练习和阅读,你一定会对这个概念感到满意。 :) – Nitish 2011-03-23 04:13:27

相关问题