在后台线程中加载UIImage [英] Load UIImage in background Thread
问题描述
是否可以在后台线程中加载UIImage而不会导致线程问题?
如果不是最好的方法是什么?我正在使用iOS 8.这就是我现在这样做的方式:
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];
});
});
推荐答案
你所做的是结构合理,但我不知道 imageNamed:
是否是线程安全的 - 我没有理由相信它是。除非文档另有说明,否则您应该始终认为事情不是线程安全的。在这种情况下,文档明确说明它不:
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.
在我看来,你应该问自己是否需要这样做。 imageNamed:
包含一个缓存机制,可以减轻您担心的任何问题。无论如何,过早优化会浪费你的时间和智力。这里真的有问题吗?用仪器找出;不要使用直觉或直觉。
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.
如果问题是您的图像太大而且格式选择不当 - 例如,您使用的是非常大的JPEG - 最好集中精力纠正 。
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.
编辑 iOS 9文档现在说:在iOS 9及更高版本,此方法是线程安全的。这表明我的答案都是正确的,问题现在已经解决了。
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.
这篇关于在后台线程中加载UIImage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!