Adrian Bartholomew Adrian Bartholomew - 5 months ago 18
Swift Question

Observe property change of class instance

Given an instance of a class, how can I observe a property change?
For e.g., I'm building an SDK that initializes a host app's chat view to provide more functionality with a simple inplementation that looks like:


In that initializing function, I need to track the host app's chat-view's
property so that the SDK's view matches.


A simple KVO example for observing hidden:

class SDKViewController : UIViewController {
    private var context = 0
    private var observingView: UIView?

    func initialize(view: UIView) {

        observingView = view

        // start observing changes to hidden property of UIView
        observingView?.addObserver(self, forKeyPath: "hidden", options: [.New], context: &context)

    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        if let newValue = change?[NSKeyValueChangeNewKey] as? Bool where context == &self.context {
            print("hidden changed: \(newValue)")

    // this is called by deinit
    // it should also be called if they can deregister the view from your SDK
    func removeObservations() {
        if let view = observingView {
            view.removeObserver(self, forKeyPath: "hidden")
            observingView = nil

    deinit {

This is making some assumptions about your configuration, but if you allow initialization of many views, you can adjust easily.

Also, a lot of this is more concise if you use KVOController by Facebook, which is not in Swift.

Edit: Just to note, hidden does work with KVO.

Edit #2: Updated YourSDKClass to SDKViewController (NSObject -> UIViewController)