I have a UITableView
that populates its cells with thumbnail images. In my case, the thumbnails are downloaded from a server. My code is as follows:
if (![self thumbnailExists])
{
self.thumbnailImageView.image = nil;
[self.activityIndicatorView startAnimating];
NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:
^{
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:self.thumbnailURL]];
UIImage *image = [UIImage imageWithData:data];
[[NSOperationQueue mainQueue] addOperationWithBlock:
^{
SubmenuScrollViewTableViewCell *submenuScrollViewTableViewCell = (SubmenuScrollViewTableViewCell*)[(UITableView*)self.superview cellForRowAtIndexPath:self.indexPath];
[submenuScrollViewTableViewCell.activityIndicatorView stopAnimating];
submenuScrollViewTableViewCell.thumbnailImageView.image = image;
}];
}];
[self.operationQueue addOperation:operation];
[self.operationQueues setObject:operation forKey:[self title]];
}
This code is based on the great WWDC2012 presentation: "Building Concurrent User Interfaces on iOS". The main difference between my code and the code in the presentation is I'm populating my cells with data that is retrieved from the web.
It works well for the most part, but the problem I'm having is if I scroll really fast, then one of the cells might show up with the wrong thumbnail (usually I noticed said cell would be a multiple of the cell from which the thumbnail belongs to). I should mention this code is being executed in the layoutSubviews
method of an overridden UITableViewCell
.
Can anyone spot any flaws in this code?
The issue had to do with the fact that the above code was in the layoutSubviews method of a subclassed UITableViewCell I created. When I moved it back in the cellForRowAtIndexPath method, the problem was eliminated.