Load UIImage in the background

Is it possible to load UIImage on a background thread without threading issues? If this is not the best way to do it? I am using iOS 8. This is how I am doing 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];
        });

    });

      

+3


source to share


1 answer


What you are doing is structurally sound, but I do not know if it is imageNamed:

thread safe - and I have no reason to believe that it is. You should always assume that things are not thread safe unless the documentation states otherwise. In this case, the documentation states that it is not:

You cannot assume this method is thread safe.

In my opinion, you should ask yourself if you need to do this at all. imageNamed:

includes a caching mechanism that should free you from what's bothering you. In any case, premature optimization is a waste of your time and opportunities. Is there really a problem here? Use tools to find out; don't use intuition or instinct.



If the problem is that your images are too large and have poor format choices - for example, you are using very large JPEG files, it might be better to focus on fixing that.

EDIT The iOS 9 documentation now says, "In iOS 9 and later, this method is thread safe." This suggests that my answer was correct and that the problem has now been resolved.

+11


source







All Articles