-
Apple 官方描述
“Use a weak reference whenever it is valid for that reference to become nil at some point during its lifetime. Conversely, use an unowned reference when you know that the reference will never be nil once it has been set during initialization.”
翻譯:在引用對象的生命周期內(nèi),如果它可能為nil
,那么就用weak
引用残吩。反之税迷,當(dāng)你知道引用對象在初始化后永遠(yuǎn)都不會為nil
就用unowned
.**
現(xiàn)在你就知道了:就像是implicitly unwrapped optional(隱式可選類型),如果你能保證在使用過程中引用對象不會為nil
,用unowned
。如果不能,那么就用weak
.
下面就是個很好的例子裆馒。Class
里面的閉包捕獲了self
,self
永遠(yuǎn)不會為nil
丐怯。
class RetainCycle {
var closure: (() -> Void)!
var string = "Hello"
init() {
closure = { [unowned self] in
self.string = "Hello, World!"
}
}
}
在這個例子中领追,由于我們在初始化RetainCycle
類后立即調(diào)用了閉包,所以我們可以認(rèn)為self
永遠(yuǎn)不會為nil
响逢。