Problem with table view in iPhone when adding image to it

i have following code to create cell and add image to it

UIImageView* MyImage =[[UIImageView alloc]initWithFrame:CGRectMake(100,10,40,40)];  
[MyImage setImage:[UIImage imageNamed:[imageArray objectAtIndex:indexPath.row]]];  
[MyImage setBackgroundColor:[UIColor clearColor]];  
[cell addSubview:MyImage];  
[MyImage release];  

cell.textLabel.text=[dataArray objectAtIndex:indexPath.row];  
     return cell;

I am using this table for many purposes and therefore refreshing it again and again.... Therefore next i age overlaps the last one due to which problem occurs and both of these images are visible(i am using transparent background for each image).... other problem occurs when i need no image..here i am unable to remove the last image ...

please help

Answers


As you might be aware that when you reuse cell from 'dequeueReusableCellWithIdentifier', it returns you existing cell instance if present, that means if cell exist its data also exists i.e. image, so you need to clear the old image before updating the cell with new data as if new data doesn't have image then it will show old image, I guess you got the point...

Ok here is the solution:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if(cell==nil)
{
   cell = [[UITableViewCell alloc] initWithStyle:UITableViewStyleDefault reuseIdentifier:cellIdentifier];

   UIImageView* MyImage =[[UIImageView alloc]initWithFrame:CGRectMake(100,10,40,40)]; 
   MyImage.tag = 1000; 

   [MyImage setBackgroundColor:[UIColor clearColor]];  
   [cell addSubview:MyImage];  
   [MyImage release]; 
}
UIImageView *imgView = (UIImageView*)[cell viewWithTag:1000];
imgView.image = nil;
imgView.image = [UIImage imageNamed:[imageArray objectAtIndex:indexPath.row]];

Need Your Help

iOS 5 + ARC - does assigning nil to pointer free up memory?

ios memory-management automatic-ref-counting

I'm trying to conform to Apple's guidelines about responding to low memory warnings in my app. The guidelines say: "Upon receiving (a low memory warning), your application must free up as much memo...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.