使用 KVO 判断元素何时被添加到数组中

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

我想使用 KVO 检查是否已将元素添加到 swift 中的数组中,我基本上是从 Apple 的文档中复制示例,但是当代码运行时,它没有捕捉到阵列更新。这是我现在拥有的:

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)
    }
}

将节目添加到数组后,我将 showCount 设置为数组中元素的数量,但是,它不会将 "X shows were added" 打印到控制台。我的 viewDidLoad() 函数只是调用将元素添加到数组的函数,目前没有其他任何东西。

很遗憾,您不能将观察者添加到 Int,因为它不会子类化 NSObject

查看 Apple Docs 并搜索 "Key-Value Observing"

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

否则,您的 KVO 样板代码对我来说看起来不错。

如果您想在数组内容更改时收到通知,可以尝试@Paul Patterson 推荐的方法和