-1

I have a UITableView, which I fill this way:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MyData *myData = [arrayData objectAtIndex:indexPath.row];
    MyTableViewCell *cell = [[MyTableViewCell alloc] init:myData.title
                                                         :myData.url];
    return cell;
}

There is an UIImageView in MyTableViewCell, I load it like this:

- (id) init : (NSString *) parTitle : (NSString *) parUrl {
    // ...
    [self load:parUrl];
    // ...
}

- (void) load : (NSString *) url {
    NSURL *myURL = [NSURL URLWithString:url];

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
        image = [[UIImageView alloc] initWithFrame:CGRectMake(0, 18, 70, 65)];
        NSData *imageData = [NSData dataWithContentsOfURL:myURL];
        dispatch_async(dispatch_get_main_queue(), ^{
            // Update the UI
            [image setImage:[UIImage imageWithData:imageData]];
            image.contentMode = UIViewContentModeScaleAspectFit;
            [self.contentView addSubview:image];
            [self reloadInputViews];
        });
    });
}

The problem is that every time a cell disappears from the screen, it reloads its content when I scroll back, but I don't want it. What to do? Thanks for your help.

Rob
  • 15,732
  • 22
  • 69
  • 107

2 Answers2

1

You simply need a more sophisticated solution. Store the downloaded image in the model and check for that up front, so that if the image has already been downloaded, you don't download it again.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • 1
    The problem of dynamically downloading images for a table view lazily is heavily discussed on Stack Overflow and elsewhere, so there's no need for you to reinvent this wheel. Just do a search. – matt Jul 23 '14 at 19:24
  • My own implementation is here: http://github.com/mattneub/Programming-iOS-Book-Examples/blob/master/bk2ch24p842downloader/ch37p1099downloader/MyTableViewController.m – matt Jul 23 '14 at 19:26
1
  • I think missing part is [tableView dequeueReusableCellWithIdentifier:@"CellIdentifier"]; Always reuse the cells.
  • You can cache the images, there are plenty of method to cache the image for iOs. Best way to cache images on ios app?
Community
  • 1
  • 1
Wagh
  • 2,678
  • 1
  • 25
  • 29