ios - 哪些类不符合 KVO 标准?

标签 ios key-value-observing nsobject kvc

下面是 Apple 文档中的两个不同段落。在一段中,它说所有继承自 NSObject 以使用 KVO 的类都是 KVO 兼容的。在第二段中,它表示并非所有类都符合 KVO。哪些类不符合 KVO?有没有不继承NSObject的类?而我知道所有继承自 NSObject

最好举个例子,了解两段之间的区别。

To use KVO, first you must ensure that the observed object, the Account, in this case, is KVO compliant. Typically, if your objects inherit from NSObject and you create properties in the usual way, your objects and their properties will automatically be KVO Compliant. It is also possible to implement compliance manually. KVO Compliance describes the difference between automatic and manual key-value observing, and how to implement both.

Important: Not all classes are KVO-compliant for all properties. You can ensure your own classes are KVO-compliant by following the steps described in KVO Compliance. Typically properties in Apple-supplied frameworks are only KVO-compliant if they are documented as such.

最佳答案

要使对象的属性符合 KVO,对象必须继承 NSObject 并且对象还必须:

  • 仅使用属性的 setter 方法更新属性,或者
  • 修改属性时手动通知。

由于您没有 Apple 框架的源代码,您通常无法知道 Apple 提供的类的对象是否符合这些要求中的任何一个,除非通过检查文档。如果文档说一个属性是 KVO 兼容的,你就知道它符合。否则,您不知道它是否符合要求,因此在该属性(property)上使用 KVO 是不安全的。

重要的是要了解属性有时可能以符合 KVO 的方式更新,有时则以不兼容的方式更新。所以你不能只做一个简单的测试来决定!您的测试可能表明该属性对于您设置属性的方式是符合 KVO 的,但它不能表明该属性总是以 KVO 兼容的方式更新。

例如,每个 UIView 都拥有一个 CALayer,以及许多 UIView 的属性,包括它的 frame、它的 bounds 和它的 backgroundColor 实际上是那个 CALayer 的属性。当您在 View 上获取或设置属性时, View 的访问器方法只是将消息发送到图层。但您也可以直接设置图层的属性。所以如果你说 view.bounds = someRect, View 可能会通知 KVO 观察者。但是如果你说 view.layer.bounds = someRect, View 将通知 KVO 观察者。但是在这些语句中的任何一个之后,view.bounds 将返回 someRect

因此,如果您负责该属性的实现,或者如果该属性被记录为符合 KVO,则您只能依赖该属性符合 KVO。

关于ios - 哪些类不符合 KVO 标准?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42882715/

相关文章:

iphone - NSObject类中是否需要写init方法

ios - UIView transform.scaleBy 动画不工作

swift - Swift 中键值编码的使用

cocoa - 为什么 Cocoa 绑定(bind)同时使用 KVC 和 KVO 而不仅仅是 KVC?

swift - 如何在 Swift 4 中使用带有智能键路径的键值观察?

ios - 如何在 NSObject 类中显示 UIAlertView?

Xcode代码补全提示 `printContent(_)`以上 `print(_)`

ios - 在 swift 的 navigationStack 之上重用相同的 viewController

iphone - 在特定时间执行某项功能

iphone - 位置和标题不起作用