【问题标题】:Unowned Self in instance variables raising issue实例变量中的 Unowned Self 引发问题
【发布时间】:2016-10-11 22:34:22
【问题描述】:

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

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

【问题讨论】:

  • 你为什么不把这个属性变成一个函数?

标签: ios swift


【解决方案1】:

问题是在第一阶段初始化完成之前,您不能使用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

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

【讨论】:

  • 完美答案,非常感谢。我被诊断信息误导了
猜你喜欢
  • 2010-12-14
  • 1970-01-01
  • 2012-04-04
  • 1970-01-01
  • 1970-01-01
  • 2012-05-02
  • 2011-06-10
  • 1970-01-01
  • 2018-08-26
相关资源
最近更新 更多