I have a table view with custom cells. Every cell has an image, title, and a description. When I first load the table, it loads fine. if I slowly scroll trough the images, also seems to work fine. As soon as I scroll down fast (assuming the number of cells is large enough to not fit in without scrolling up and down) the images start to changes cells in a random order. Some cells have the same image twice.
Any clue why this is happening?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
BookmarkCellViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
NewsArticle *currArt = [self.lN_Dept objectAtIndex:indexPath.row];
if(currArt.artImage == Nil)
{
if([currArt.mainImage_URL rangeOfString:@"<img src="].location != NSNotFound)
{
NSRange range = [currArt.mainImage_URL rangeOfString:@"<img src=\"/CONC/"];
NSString *substring = [[currArt.mainImage_URL substringFromIndex:NSMaxRange(range)] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSRange range2 = [substring rangeOfString:@"\""];
NSString *substring2 = [[substring substringToIndex:NSMaxRange(range2)-1] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSString *imageURL = [PUB_URL stringByAppendingString:substring2];
[self downloadImageWithURL:[NSURL URLWithString:imageURL] completionBlock:^(BOOL succeeded, UIImage *image) {
if (succeeded) {
currArt.artImage = image;
cell.ArtDisplayImage.image = currArt.artImage;
}
}];
}
}
else
{
cell.ArtDisplayImage.image = currArt.artImage;
}
[cell configureCellForEntry:currArticle];
return cell;
}
- (void)downloadImageWithURL:(NSURL *)url completionBlock:(void (^)(BOOL succeeded, UIImage *image))completionBlock
{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *Data, NSError *error) {
if ( !error )
{
UIImage *image = [[UIImage alloc] initWithData:Data];
completionBlock(YES,image);
} else{
completionBlock(NO,nil);
}
}];
}