前提条件 Swift 3

Precondition Swift 3

我正在关注 Apple 上次关于 GCD 的会议link:https://developer.apple.com/videos/play/wwdc2016-720/?time=33 我到了这里谈到前提条件的地步:https://developer.apple.com/videos/play/wwdc2016-720/?time=1267,Swift 3 中的一个新功能。 到达这里: https://developer.apple.com/videos/play/wwdc2016-720/?time=1474 是这样使用的: .register(观察者:,队列:) 我的问题:这个函数如何保留 object BusyControllerhttps://developer.apple.com/videos/play/wwdc2016/720/?time=1550

你问这个register(observer:queue:)怎么保留BusyController.

首先,让我们退后一步:我们不要迷失在他的例子的细节中。他并不是说它 建立一个强大的参考,只是说它 可以 ,因此你应该谨慎尝试清理 deinit.

那么,DataTransform怎么可能留住BusyController呢?它可以简单地保持对其 observer 的强引用。请注意,不要将此自定义 register 方法示例与标准观察者方法混为一谈:它们只是在说 "imagine that the DataTransform object established a strong reference to BusyController..."

但是,正如他接着说的那样 "but you're skilled developers, and you know how to fix this problem; use a weak reference." 所以,一般来说,我们不会编写保持对其观察者的强引用的观察方法。

但是,正如他接着说的那样,即使您善于避免强引用循环,对象图也会变得相当复杂,因此依赖 deinit 并不总是一个好主意清理。他提倡显式 invalidate 过程,并可能使用先决条件来测试对象在调用 deinit 时是否已失效。