gpt4 book ai didi

swift - Unowned 引用如何与 Swift 中的捕获变量一起使用

转载 作者:行者123 更新时间:2023-11-28 05:45:16 29 4
gpt4 key购买 nike

关于 ARC 的教程很多。但我不理解 unowned 或 weak 的明确工作原理,因为引用捕获的变量如何变为 null。

苹果文档:

Define a capture in a closure as an unowned reference when the closure and the instance it captures will always refer to each other, and will always be deallocated at the same time.

class RetainCycle {
var closure: (() -> Void)!
var string = "Hello"

init() {
closure = { [unowned self] in
self.string = "Hello, World!"
}
}
}

闭包在其主体内引用 self(作为引用 self.string 的一种方式),闭包捕获 self,这意味着它持有对 RetainCycle 实例的强引用。两者之间形成了强引用循环。由 unowned 打破引用循环。

但我想了解哪种情况两者不会相互同时解除分配并且 Unowned self 变为 null 只是想让它崩溃。?

最佳答案

据我了解,您会问在 closue 运行时如何将 self 设为 null。如果我做对了,我可以给你一个我以前见过的非常相似的例子。

我写了一个 UIImageView 的扩展,它从给定的链接下载图像并像这样设置自己。

public extension UIImageView{
func downloadImage(link: String){
let url = URL(string:link)
URLSession.shared.dataTask(with: url){ [unowned self]
if let image = UIImage(data: data){
DispatchQueue.main.async{
self.image = image
}
}
}
task.start()
}
}

但是有一个问题。下载图像是一项后台任务。我将完成方法设置为 UrlSession 并增加了它的引用计数。因此,即使 imageView 被取消分配,我的闭包仍然存在。

那么,如果我在下载完成之前关闭保存我的 UIImageViewviewController 会发生什么。它崩溃是因为 imageView 被释放,但闭包仍然存在并试图访问它的 image 属性。据我了解,您想学习这个。

我将 unowned 引用更改为 weak 来解决这个问题。

关于swift - Unowned 引用如何与 Swift 中的捕获变量一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55001921/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com