Reputation: 559
I'm using this code for loading my images in a UITableView using custom cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"CustomCell";
CustomCell *cell = (CustomCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];
for (id currentObject in topLevelObjects) {
if ([currentObject isKindOfClass:[CustomCell class]]) {
cell = (CustomCell *) currentObject;
break;
}
}
NSString *tempString = [arrayThumbs objectAtIndex:indexPath.row];
NSURL *imageURL = [NSURL URLWithString:tempString];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *image = [UIImage imageWithData:imageData];
cell.img.image = image;
}
return cell;
}
with the above code, there is no problem when scrolling up and down, but the images doesn't show correctly, some images are repeated in the table , example for that if the array holds 10 images from 1 to 10 and the array is correct in the order, the images i get in the table something like 1 , 2 , 3 , 4 , 3 , 3 , 1 , 10 , 8 , 9
but when i use this code
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"CustomCell";
CustomCell *cell = (CustomCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];
for (id currentObject in topLevelObjects) {
if ([currentObject isKindOfClass:[CustomCell class]]) {
cell = (CustomCell *) currentObject;
break;
}
}
}
NSString *tempString = [arrayThumbs objectAtIndex:indexPath.row];
NSURL *imageURL = [NSURL URLWithString:tempString];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *image = [UIImage imageWithData:imageData];
cell.img.image = image;
return cell;
}
the images are ordered fine and no duplicates but when i scroll to the bottom of the table then scrolling back to the top the table freeze for 2 or 3 seconds
any idea how to solve this ?
the array contain links for the images like http://www.website.com/image.jpg
custom cell contain IBOutlet UIImageView 60x60 and the images that loads from the server are also 60x60
Upvotes: 1
Views: 2581
Reputation: 7227
try the following code to download the image in the thread.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSString *tempString = [arrayThumbs objectAtIndex:indexPath.row];
NSURL *imageURL = [NSURL URLWithString:tempString];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *image = [UIImage imageWithData:imageData];
dispatch_async(dispatch_get_main_queue(), ^{
cell.img.image = image;
});
});
Upvotes: 8