gpt4 book ai didi

ios - 实例变量中的 Unowned Self 引发问题

转载 作者:行者123 更新时间:2023-11-28 12:39:06 26 4
gpt4 key购买 nike

我正在尝试创建一个闭包来清除我的缓存,这两个都是实例变量。当我尝试调用 [unowned self] 时,出现错误“‘unowned may only be applied to class and class-bound protocol types, not (UIViewController) -> () -> UIViewController'”...我是不知道为什么要提出这个问题。在实例变量中调用 self 是否没有创建保留循环?如果是这样,为什么?提前谢谢你,这里是相关的代码片段

class UIViewController
{
var repostCache : [String : Bool] = [String : Bool]()
let clearRepostCache = { [unowned self] in
self.repostCache = [String : Bool]()
}
}

最佳答案

问题是在 phase1 初始化完成之前,您不能使用 self。因此,您不能使用 self 作为属性的初始值。

您可能需要将使用 self 的代码移动到某个实例方法中(或在阶段 1 初始化后移动到初始化程序中)。

例如:

class ViewController: UIViewController {
var repostCache: [String: Bool] = [:]
private(set) var clearRepostCache: (()->Void)!
override func viewDidLoad() {
clearRepostCache = { [unowned self] in
self.repostCache = [:]
}
}
}

您可以在此处找到有关两阶段初始化的文档:

Class Inheritance and Initialization

关于令人困惑的诊断消息,最好发送错误报告。

关于ios - 实例变量中的 Unowned Self 引发问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39987818/

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