Search code examples
arraysswiftkey-value-observing

Using KVO to tell when elements have been added to an array


I want to check if elements have been added to an array in swift using KVO, and I essentially copied the example from Apple's documentation, but when the code runs, it does not catch when the size of the array updates. Here is what I have now:

class ShowDirectory: NSObject {
    var shows = [Show]()
    dynamic var showCount = Int()
    func updateDate(x: Int) {
        showCount = x
    }
}

class MyObserver: NSObject {
    var objectToObserve = ShowDirectory()
    override init() {
        super.init()
        objectToObserve.addObserver(self, forKeyPath: "showCount", options: .New, context: &myContext)
    }

    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        if context == &myContext {
            if let newValue = change?[NSKeyValueChangeNewKey] {
                print("\(newValue) shows were added")
            }
        } else {
            super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
        }
    }

    deinit {
        objectToObserve.removeObserver(self, forKeyPath: "myDate", context: &myContext)
    }
}

After I add the shows to the array, I set showCount equal to the number of elements in the array, however, it does not print "X shows were added" to console. My viewDidLoad() function simply calls the function that adds elements to the array, and nothing else at the moment.


Solution

  • You unfortunately cannot add as an observer to an Int, as it does not subclass NSObject

    See the Apple Docs and search for "Key-Value Observing"

    You can use key-value observing with a Swift class, as long as the class inherits from the NSObject class.

    Otherwise, your KVO boiler-plate code looks good to me.

    If you want to be notified when your array's contents change, you could try what @Paul Patterson recommends and use a proxy object