Swift Selectors and Closures Discussion

喜夏-厌秋 提交于 2019-12-04 19:03:56

In your case at the moment, it seems that no cyclic-reference is formed. But it's possible to accidentally be formed in the future. Like the followings for the instance.

// In the `Test` class.
let control = MyControl()
init() {
    control.addClosureFor(UIControlEvents.TouchUpInside, closure: { (control) -> () in
        self.testProperty = "This is making a reference cycle?"
    })
}

In this code, self has a reference to the control as its field and the control has a reference to self through the closure added by addClosureFor. This forms a cyclic reference so these objects in the cycle are never released.

closure capture list helps this issue.

control.addClosureFor(UIControlEvents.TouchUpInside) { [weak self] /* <-- */ control -> () in
    // Here, `self` is visible as `Optional<Test>` so the `?` operator is required.
    self?.testProperty = "This is making a reference cycle?"
    return
}

In the block in this code above, self is weakly captured so that an only one unidirectional reference is formed from self to the control. Note that, now in the closure, the access to self isn't assured because self is weakly-referenced. You have to consider self an optional value.

https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/AutomaticReferenceCounting.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!