Is it possible to load a UIImage in a background thread without causing threading problems? If not what is the best way of doing it? I'm using iOS 8. This is the way I do it right now:
dispatch_queue_t backgroundQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);
dispatch_async(backgroundQueue, ^{
UIImage *image = [UIImage imageNamed: fileName];
// only update UI on the main thread
dispatch_async(dispatch_get_main_queue(), ^{
[self setImage: image];
});
});
What you're doing is structurally sound, but I don't know whether imageNamed:
is thread-safe — and I have no reason to believe that it is. You should always assume that things are not thread-safe unless you are told otherwise by the documentation. In this case, the documentation specifically says that it is not:
You can not assume that this method is thread safe.
In my view, you should ask yourself whether you need to do this at all. imageNamed:
includes a caching mechanism that should relieve you of whatever you are worried about. In any case, premature optimization is a waste of your time and brainpower. Is there really an issue here? Use Instruments to find out; don't use intuition or instinct.
If the problem is that your images are too large and in a bad choice of format — for example, you are using very large JPEGs — it would be better to concentrate on correcting that.
EDIT The iOS 9 documentation now says: "In iOS 9 and later, this method is thread safe." This suggests both that my answer was correct and that the problem is now solved.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With