迅速弱的自我保留功能

时间:2015-06-18 20:53:28

标签: swift automatic-ref-counting

如果我有一个引用weak var weakSelf = self的闭包,我可以通过weakSelf将该闭包更改为直接函数引用吗?

struct ClosureHolder {
    let closure: () -> Void
}

class ClosureSource {
    func hello() {
        NSLog("hello")
    }

    func createWeakSelfWithinInnerClosureClosureHolder() -> ClosureHolder {
        weak var weakSelf = self
        return ClosureHolder(closure: {
            weakSelf?.hello()
        })
    }

    func createWeakSelfDotHelloClosureHolder() -> ClosureHolder {
        weak var weakSelf = self
        // The code below won't compile because weakSelf is an Optional.
        // Once I unwrap the optional, I no longer have a weak reference.
        // return ClosureHolder(closure: weakSelf.hello)

        // this strongifies the weak reference. :(
        return ClosureHolder(closure: weakSelf!.hello)
    }
}

而不是createWeakSelfWithinInnerClosureClosureHolder,我更喜欢createWeakSelfDotHelloClosureHolder

1 个答案:

答案 0 :(得分:3)

不,你不能。说self.foo(如果foo是一种方法)与说MyClass.foo(self)完全相同。以这种方式计算的方法始终保持对接收器对象的强烈参考。如果你想保持弱引用,那么你需要坚持使用{ weakSelf?.hello() }方法。