Understanding KVO in iOS

本小妞迷上赌 提交于 2019-11-30 13:18:35

问题


Regarding "Ensuring KVO Compliance", there are some official definition which seem like hard to understand

In order to be considered KVO-compliant for a specific property, a class must ensure the following;

  1. The class must be key-value coding compliant for the property as specified in Ensuring KVC Compliance.

  2. The class must allow automatic observer notifications for the property, or implement manual key-value observing for the property.

Who can give more specific examples to make this more clear ? Thanks


回答1:


Take a look at Ensuring KVO Compliance the Automatic Versus Manual Support section of the Key-Value Observing Programming Guide. Compliance is essentially achieved by following naming conventions for methods and/or ivars.

In my experience KVO tends to 'just work', which is nice.




回答2:


When you use @property tags to create getters/ setters the magic is auto wired for To-One relationships and you only need to addObserver... and implement the observe... method to catch the updates.

The real challenge is understanding how you implement To-Many Key Value Compliance to make a mutable set or array work. The documentation here is key and the understanding that there are two sections... Indexed collections and Unordered collections. It really helped me to understand that if my @property is an NSMutableArray you need to look at the methods in the Indexed area and if your @property is a NSMutableSet you need to look at the Unordered documentation.

There are Required methods that you need to implement even if you don't plan to use them.



来源:https://stackoverflow.com/questions/4813331/understanding-kvo-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!