我正在异步创建图像,然后在主线程上更新 UI。例如
imageLoadingQueue.async {
// Creates a new image, caches it.
let newImage = ImageManager.shared.buildImage(named: ...)
DispatchQueue.main.async {
view.setImage(newImage)
}
}
但是,我担心后台线程上与缓存有关的操作。
在这种情况下,ImageManager 单例负责所需图像的创建和缓存(通过共享实例上的 NSCache
属性)。
问。 buildImage(named:)
方法将构建的图像缓存在“共享”的属性中是否安全?
如果不是,buildImage(named:)
方法在主线程上执行缓存是否安全,因此:
func buildImage(named name: String) -> UIImage
{
let newImage = ... // Do the work.
// Cache the result on the main thread, to our property.
DispatchQueue.main.async {
self.imageCache[key] =
}
return newImage
}
或者...
另一种可能性:将图像创建与缓存分开。我不喜欢这种人为的分解,因为它让 ImageManager 的使用者做更多事情,但采用它更安全。
imageLoadingQueue.async {
// Build the image. Performs no caching.
let newImage = ImageManager.shared.buildImage(named: ...)
DispatchQueue.main.async {
// Cache the image now that we're on the main thread.
ImageManager.shared.cacheImage(image, key: "foo")
view.setImage(newImage)
}
}
如有任何建议,我们将不胜感激。
最佳答案
您的问题有点开放性。但是,我认为您正在寻找的答案非常简单。 NSCache
documentation部分说:
- You can add, remove, and query items in the cache from different threads without having to lock the cache yourself.
所以对于你的问题,
Q. is it safe for the buildImage(named:) method to cache the built image in a property on 'shared'?
是的,您可以在任何线程上修改缓存,而无需采取您自己的线程安全预防措施,例如异步分派(dispatch)到主线程。
关于iOS DispatchQueue 在后台线程缓存的安全性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43359317/