Image in the TableView Cell causes delay when scrolling
I've put an image into my tableview cell in which the image is located in a certain URL.. My problem is that when my tableView already displays the data, then scrolling the tableview up & down, it will take some time or delay before it reacts to the scrolling..
I've found out the problem is into the image located in the URL and I need also to display each image in the tableview cell. Any idea how I can fix it? or to be optimize?
Here's my code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
// Set up the cell
NSUInteger row = [indexPath row];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
开发者_如何学GoNSArray *arrLocal = [m_list objectAtIndex:row];
if ([arrLocal count] > 0) {
cell.textLabel.text = [arrLocal objectAtIndex:2];
cell.textLabel.font = [UIFont boldSystemFontOfSize:14];
cell.detailTextLabel.text = [arrLocal objectAtIndex:3];
cell.detailTextLabel.font = [UIFont systemFontOfSize:12];
//sample url of the image: http://www.mysite.com/images/DealExtreme/2657_1_small.jpg
NSString *strTemp = [[NSString alloc] initWithString:@"http://www.mysite.com/"];
NSString *urlString = [strTemp stringByAppendingString: [arrLocal objectAtIndex:1]];
NSURL *url = [NSURL URLWithString:urlString];
UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]];
cell.imageView.image = image;
[strTemp release];
}
return cell;
}
The problem is that you are downloading the image everytime cellForRow is called, i would suggest you load the images in the background... One way to do it is make your custom cells, have them have a method or something of the sort that will load the image in the background then set it, another way could be to load all your images in the background and keep them around, then set the cells images, that way you arent reloading an image everytime the cell comes on the screen...hope it helps
You must load that image data asynchronously or you are blocking the main thread. You will certainly want to avoid this. It makes your app unresponsive, and if the delay is big enough, your app might easily get killed by the OS.
So start to download the image in background (using NSURLRequest
and NSURLConnection
) and refresh the cell's content when the data is complete.
精彩评论