I have a UICollectionView displaying a grid of custom cells. When I setup the cell in cellForItemAtIndexPath I call a method on the cell subclass to setup the UI (e.g. [cell setupUI]). This method does some loading of labels but also calls an async method which fetches images from the web. I'm using AFNetworking to handle this.
My issue is that sometimes (quite often) the images get loaded in the correct cells + cells that shouldn't have an image set. The data just seems to get loaded in random cells.
I've been looking at this for a while and tried multiple approaches but I can't figure out where I'm going wrong. Is there a gotcha I'm missing?
NB: I've checked and the method that sets these image cells is called the correct number of times (3) but images appear on 5 cells.
Edit
This is the code used to fetch the images. I've previously used this without CollectionView (drawing the grid myself) and it worked fine:
[self.youtubeThumbnail setImageWithURLRequest:request placeholderImage:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image){
weakImageView.image = image;
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error){
}];
weakImageView is a weak reference to my cells image view. The above code is in the cell subclass and is called from cellForItemAtIndexPath.
I should point out this method is run on dispatch_async(dispatch_get_global_queue) and the image loading is on dispatch_async(dispatch_get_main_queue).
Solution
So my problem was actually quite strange. My collection view was being reloaded multiple times and this caused the data to appear multiple times in incorrect cells. I'm still not 100% sure why this is the case but I have managed to hack around it by checking if the content has been reloaded, setting a BOOL, and preventing a reload again. The answer I have selected is correct helped my get the async loading correct which was also likely part of the issue. Thanks for your help.