简体   繁体   中英

Async image loading from url inside a UITableView cell - image changes to wrong image while scrolling?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{   static NSString *CellIdentifier = @"cell";

    TVcell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    if (cell == nil)
        cell = [[TVcell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

   cell.txtlabel.text = [[[arrayData objectAtIndex:indexPath.row] valueForKey:@"description"]stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];


    cell.IMGLabel.contentMode = UIViewContentModeScaleAspectFill;
    cell.IMGLabel.image = nil;

    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@",[enclosureUrlArray objectAtIndex:indexPath.row]]];

    NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data) {
            UIImage *image = [UIImage imageWithData:data];
            if (image) {
                dispatch_async(dispatch_get_main_queue(), ^{
                        cell.IMGLabel.image = image;
                          [cell.IMGLabel setImage:image];
                          [cell.IMGLabel.layer setMasksToBounds:YES];
                          [cell.IMGLabel.layer setCornerRadius:2.5f];
                          [cell setNeedsLayout];

                });
            }
        }
    }];
    [task resume];

Your problem is that you have no guarantee that your NSUrlRequests will terminate in the same order than they started. This is bad because your cells are re-used for better performance and it can end with strange behavior.

You can find a fix here: Asynchronous downloading of images for UITableView with GCD

Or you can use tools listed here to help you address this issue: https://stackoverflow.com/a/32601838/3769338

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM