知道当一个弱variables在Swift中变成零时?

比方说,我有一个weak var view: UIView? 在我的class Button {} 。 有什么方法可以知道什么时候view丢失了它的参考,并成为nil

我试过使用weak var view: UIView? {} weak var view: UIView? {} (又名一个计算属性),以覆盖set {} ,但没有工作,因为现在它是一个计算属性,不能存储一个弱引用(多烦人!)。

编辑:

@fqdn的答案没有用这个代码…在Xcode游乐场试试吧

 import UIKit class Test { weak var target: UIView? { willSet { if !newValue { println("target set to nil") } else { println("target set to view") } } } } class Button { var view: UIView? = UIView() } var t = Test() var b = Button() t.target = b.view b.view = nil // t.target's willSet should be fired here 

您的输出控制台应显示:

 target set to view target set to nil 

我的控制台显示

 target set to view 

b.view是UIView实例的强大参考。 t.target是弱引用。 因此,如果b.view设置为nil ,则解除分配UIView实例,并且t.target将等于nil。

如果你的button持有对另一个视图的引用,它应该是该视图的所有者(即它应该有一个强大的引用),或者它不应该关心视图何时消失(即,它的弱引用变成零)当弱引用变为零时,没有任何通知,这是通过devise。

特别是,弱引用变为零时,不会调用Swift属性观察器,如下面的代码所示:

 class A : CustomStringConvertible { var s: String? init(s: String) { self.s = s; print("\(self) init") } deinit { print("\(self) deinit") } var description: String { get { return "[A s:\(s ?? "nil")]" } } } class B : CustomStringConvertible { weak var a:A? { willSet { print("\(self) willSet a") } didSet { print("\(self) didSet a") } } init(a: A?) { self.a = a print("\(self) init") } deinit { print("\(self) deinit") } var description: String { get { return "[B a:\(a == nil ? "nil" : String(describing: a!))]" } } } func work() { var a: A? = A(s: "Hello") var b = B(a: a) print("\(b)") a = nil print("\(b)") ba = A(s: "Goodbye") } work() 

当调用work() ,控制台会提供以下输出:

 [A s:Hello] init [B a:[A s:Hello]] init [B a:[A s:Hello]] [A s:Hello] deinit [B a:nil] [A s:Goodbye] init [B a:nil] willSet a [B a:[A s:Goodbye]] didSet a [A s:Goodbye] deinit [B a:nil] deinit 

请注意,无论是A的解除分配的实例,还是B的实例中的弱引用,都是属性观察者所称的。 只有在直接的情况下分配给巴,他们才叫。