Let's say I have a weak var view: UIView?
in my class Button {}
. Is there any way to know when view
loses its reference and becomes nil
?
I tried using weak var view: UIView? {}
(aka a computed property) in order to override set {}
, but that didn't work because now it's a computed property and can't store a weak reference (how annoying!).
Edit:
@fqdn's answer didn't work with this code... Try it in an Xcode Playground
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
Your output console should display:
target set to view
target set to nil
My console displays
target set to view
b.view
is the strong reference for the UIView instance. t.target
is the weak reference. Therefore, if b.view
is set to nil
, the UIView instance is deallocated and t.target
will be equal to nil.