【发布时间】:2020-02-15 08:34:40
【问题描述】:
我在释放变量时遇到问题:缓存
这是来自教程Reusable Image Cache in Swift
错误:
致命错误:尝试读取无主引用但对象 0x280208080 已被释放 致命错误:尝试读取无主引用但对象 0x280208080 已被释放
代码:
final class ImageLoader {
private let cache = ImageCache()
func loadImage(from url: URL) -> AnyPublisher<UIImage?, Never> {
if let image = cache[url] {
return Just(image).eraseToAnyPublisher()
}
return URLSession.shared.dataTaskPublisher(for: url)
.map { UIImage(data: $0.data) }
.catch { error in return Just(nil) }
.handleEvents(receiveOutput: {[unowned self] image in
guard let image = image else { return }
self.cache[url] = image
})
.subscribe(on: DispatchQueue.global(qos: .background))
.receive(on: RunLoop.main)
.eraseToAnyPublisher()
}
}
【问题讨论】:
-
我很确定 ImageLoader 应该是一个单例。但这是一个很好的例子,为什么你永远不应该使用 unowned,你改变你的代码或有人复制它错误,它不仅没有做它应该做的事情,而且它也会崩溃。
-
这是来自我上面发布的链接的教程,但感谢您的评论。 @Cyberbeni
-
是的,这篇文章缺少了这一点。但是最后有一个github链接,里面有完整的源代码,说明作者也认为应该是单例:github.com/sgl0v/OnSwiftWings/blob/…