releasing all cells in tableview ios iphone
i got mem leaking problem discovered with profiling in xcode. The problem it's quite easy but i ca开发者_高级运维n't understand how fix it:
Consider a uiviewcontroller with 2 button and a tableview. button1=load JSON data from server and add cells to tableview then [tableview reloadData]
button2=load JSON data from another server and add cells to tableview then reload.
ok the problem is in:
- (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;
Ok now if i start to switch with 2 button everytime i switch i got leaking from UIImage, so i think i need to "purge" (release) all cells data before reloading?
Thx
You should be releasing the img
object after setting it in cell.imageView.image
. I prefer to autorelease
on the same line as it makes it easier for me to keep track.
UIImage *img;
if(!data) img=[UIImage imageNamed:@"small.jpg"];
else img= [[[UIImage alloc] initWithData:data] autorelease];
cell.imageView.image = img;
As mentioned in another answer, you can save yourself the pain by not using the initWithData
call, but instead imageWithData
.
The cells will take care of themselves.
The issue is not releasing img
,plz use below
if (!data)
{
img = [UIImage imageNamed:@"small.jpg"];
cell.imageView.image = img;
}
else
{
img = [[UIImage alloc] initWithData:data];
cell.imageView.image = img;
[img release];
}
I would replace this line:
else img= [[UIImage alloc] initWithData:data];
with:
else img= [UIImage imageWithData:data];
You don't have to allocate memory for UIImage. You can perform the above implementation as follows :
NSData *data = [NSData dataWithContentsOfURL:url];
cell.imageView.image = [UIImage imageWithData: data];
Try this.
精彩评论