Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

mikezang

macrumors 6502a
Original poster
May 22, 2010
939
41
Tokyo, Japan
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;
}
 
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.
 
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.
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];
 
Last edited:
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.