1

I have a UICollectionView that shows images that are brought in by JSON. It works now, but because I have around fifty images, it is very slow to scroll through the collection view. How can I improve the performance of this?

I am aware that using an asynchronous queue and/or NSCache would perhaps improve the performance as the NSCache would hold the information. I would like an implementation of this code, or a better way to do this, because I am not sure how to what is the best way to do this and how to implement that way.

Preferably, I want code that implements a good way to make this more efficient.

Eliza Wilson
  • 1,031
  • 1
  • 13
  • 38
James Mann
  • 61
  • 1
  • 7

1 Answers1

1
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    myCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) {
        cell = [[myCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }

    cell.poster.image = nil; // or cell.poster.image = [UIImage imageNamed:@"placeholder.png"];

    dispatch_async(kBgQueue, ^{
        NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://myurl.com/%@.jpg",[[myJson objectAtIndex:indexPath.row] objectForKey:@"movieId"]]]];
        if (imgData) {
            UIImage *image = [UIImage imageWithData:imgData];
            if (image) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    myCell *updateCell = (id)[tableView cellForRowAtIndexPath:indexPath];
                    if (updateCell)
                        updateCell.poster.image = image;
                });
            }
        }
    });
    return cell;
}

This is from this great answer by Rob. It talks about UITableView and not UICollectionView but the principle is the same. If you want to use a 3rd party AFNetworking is great for dealing with downloading & dealing if image cache.

Community
  • 1
  • 1
Segev
  • 19,035
  • 12
  • 80
  • 152
  • I think it's better to just link to Rob's answer via a "close" request due to a "duplicate". Rob's answer contains essential and important information about the caveats of this approach - and basically states that this code is not sufficient for a practical solution. – CouchDeveloper May 11 '14 at 05:41