swift - 新的 Key-Value Observing (KVO) 只调用 .initial 而不是 .new

标签 swift

我正在尝试找出新的 KeyValueObserving (KVO) api。我不知道我做错了什么,因为我得到 initial 观察正常但不是 newold。这就是我正在做的:

import Foundation

class Foo: NSObject {
    @objc var bar = 0
}

let foo = Foo()
let observer = foo.observe(\.bar, options: [.initial, .new, .old]) {(o, change) in
    print("old: \(change.oldValue) - new: \(change.newValue) ")
}
foo.bar = foo.bar + 1
observer.invalidate()

我得到的输出是:

old: nil - new: Optional(0) 

但我应该得到:

old: nil - new: Optional(0) 
old: Optional(0) - new: Optional(1) 

有什么想法吗?

最佳答案

记录在案here您需要在变量声明中添加 dynamic 关键字。

关于swift - 新的 Key-Value Observing (KVO) 只调用 .initial 而不是 .new,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47209747/

相关文章:

ios - UIPickerView 中的多个选定选项,其中一个部分

使用 switch、case 和 fallthrough 的 Swift 示例代码

ios - UISearchBar 对不同的值使用多个单词,iOS,Swift

swift - 在 Swift 2.x 中迭代闭区间

html - Vapor 从 MySQL 渲染 html

ios - CollectionView 滚动时更改单元格背景图像

swift - 在 Swift 中制作动画之前如何对 UILabel 应用变换?

ios - 当单元格不可见时,CellForRow 返回 nil

ios - 二元运算符 '|=' 不能应用于两个 'UIAccessibilityTraits' 操作数

ios - 如何在 UIImage 上方绘制文本以创建新图像