I have a TableView
using custom cells. I initially was setting grabbing an image from a URL in the cellForRowAtIndexPath
method
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = @"SimpleTableCell";
SimpleTableCell *cell = (SimpleTableCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"SimpleTableCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
NSDictionary *dictObject = [places objectAtIndex:indexPath.row];
cell.nameLabel.text = [dictObject valueForKey:@"PlaceTitle"];
NSURL *url = [NSURL URLWithString:@"http://images1.fanpop.com/images/image_uploads/Mario-Kart-Wii-Items-mario-kart-1116309_600_600.jpg"];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
cell.thumbnailImageView.image = image;
return cell;
}
but this was making my TableView scroll laggy. Once I removed the image fetch, it scrolled fine, so I know this is my problem.
My question is: how can I asynchronously fetch this image and set it in my cell? Is there an easy way to do this? Thanks!
dataWithContentsOfURL is a synchronous method rather than asynchronous,as Apple Documents described.
In order to asynchronously load image,especially in tableViewCell,try use 3rd part Library SDWebImage
Use this code inside your tableviews cellforindexpath
in MJTableImageView.h File
in MJTableImageView.m File
I am using StoryBoard so i add ImageClass(MJTableImageView) file to UItableviewcell ImageView and set tag number to it.
For More details see Github Project MJTableImageSwift it is in Swift.
Step 1: Have a cache containing images. Either just in memory, better on disk.
Step 2: When you need an image, call a method which either returns an image from the cache, or returns a default image and starts a download.
Step 3: When a download finishes, add the image to the cache. Then find out which rows need the image. Reload all the rows that reload the image.
The download should be done asynchronously using GCD. I would really recommend that you add the download code into a separate, reusable method so that you can handle download errors. Even if you don't do it now, you will do it later.