How to avoid loop download image in cellForRowAtIndexPath?

Discussion in 'iOS Programming' started by mikezang, Apr 20, 2012.

  1. mikezang macrumors 6502a

    Joined:
    May 22, 2010
    Location:
    Tokyo, Japan
    #1
    I use code as below to download image, but I found this code will keep downloading never stop, what can I avoid it?
    Code:
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        static NSString *CellIdentifier = @"AppSearchCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    	
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    	cell.backgroundColor = [UIColor orangeColor];
            cell.imageView.image = nil;
        }
    
    #define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
    
        dispatch_async(kBgQueue, ^{
            NSString *iconURL = [searchResultsIconURL objectAtIndex:indexPath.row];
            NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:iconURL]];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                cell.imageView.image = [UIImage imageWithData:imageData];
                [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
            });
        });
        
        return cell;
    }
     
  2. jonnymo5 macrumors 6502

    Joined:
    Jan 21, 2008
    Location:
    Texas
    #2
    First thing is that you do not want to be doing a download in this call. It will seriously slow down the loading of your table.

    As for your loop you are calling "reloadRowsAtIndexPaths" which is going to trigger cellForRowAtIndexPath

    My suggestion is to start your download in the viewDidLoad or viewWillAppear method and it will update your table without going into the loop.
     
  3. mikezang, Apr 20, 2012
    Last edited: Apr 20, 2012

    mikezang thread starter macrumors 6502a

    Joined:
    May 22, 2010
    Location:
    Tokyo, Japan
    #3
    I can't download them in viewDidLoad or viewWIllAppear, because I search web to get results, then download images base on result and update cells.

    At the moment, I got what I need, change
    Code:
    [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
    Code:
    [cell setNeedsLayout];
     

Share This Page