My situation is that my app uses core data, and needs to load images from that core data to show in a table view. Because of the time it takes to do that, it needs to run in a background thread. So i have code such as this:
dispatch_async(queue, ^{
if (self.cellInfo.numberOfMediaItems > 0) {
int i = 0;
int numberOfThumbnails = MIN(self.cellInfo.numberOfMediaItems, 3);
while (i < numberOfThumbnails) {
Media *media = [self.entry.media objectAtIndex:i];
UIImage *image = [media getThumbnail];
[self.mediaArray addObject:image];
i++;
}
}
dispatch_async(dispatch_get_main_queue(), ^{
self.isFinishedProcessing = YES;
[self setNeedsDisplay];
});
});
This speeds the process up considerably, and the images appear in the background when it's ready.
The problem is, sometimes it'll have the foreground thread try and access core data at the same time as the background thread. It doesn't like this, and so it crashes. This must be a situation that a lot of developers get in, and thus one with a solution. I wanted to know how to deal with the situation so my app stops crashing when they both start accessing core data at the same time?