4

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.

user3483203
  • 50,081
  • 9
  • 65
  • 94
  • I can't reproduce this problem. Here's my gist (from a playground): https://gist.github.com/rnapier/f3354765347631b1208892fe30e0fd31 It prints "2 shows were added." Can you post your exact code that demonstrates the problem? – Rob Napier Apr 05 '16 at 14:43

1 Answers1

1

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

Community
  • 1
  • 1
A O
  • 5,516
  • 3
  • 33
  • 68