Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
857 views
in Technique[技术] by (71.8m points)

ios - Load UIImage in background Thread

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];
        });

    });
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...