1 前言
在Objective-C中类与类之间的通信有多种方式,delegate, NSNotificationCenter 和KVO 是最常见最常用的三种技术。
2 NSNotificationCenter vs delegate
NSNotificationCenter 和 delegate的区别和使用这篇文章写得非常好,下面截取一部分出来。
A 两者
区别:
One obvious difference is that delegation is for sending a one-to-one message (to which the receiver can return a value) whereas notification is a one-to-many message (where the receivers cannot return anything to the sender).
B 两者推荐的使用原则:
1, use delegates when you want the receiving object to influence an action that will happen to the sending object.
2, use notifications when you need to inform multiple objects of an event.
2, use notifications when you need to inform multiple objects of an event.
C NSNotificationCenter的缺点:
You do not even need to add a delegate instance variable to your class. However before getting carried away with notifications it is worth being aware of the downsides. When you post a notification the notification center will deliver the message to each registered observer synchronously. Control is not returned to your code until all of the observers have had their registered method called.
3 KVO简介
其实KVO做的用NSNotification和delegate都能做到,但KVO有非常便利的地方。
KVO’s primary benefit is that you don’t have to implement your own scheme to send notifications every time a property changes. Its well-defined infrastructure has framework-level support that makes it easy to adopt—typically you do not have to add any code to your project. In addition, the infrastructure is already full-featured, which makes it easy to support multiple observers for a single property, as well as dependent values.
当Model层的某个属性发生改变时我们不需手动post消息就能触发Observer的方法,这个是NSNotification和delegate都做不到的,因为KVO 是 NSObject 内建支持的,使用上非常便利。
KVO概述
Key-value observing provides a mechanism that allows objects to be notified of changes to specific properties of other objects. It is particularly useful for communication between model and controller layers in an application. (In OS X, the controller layer binding technology relies heavily on key-value observing.) A controller object typically observes properties of model objects, and a view object observes properties of model objects through a controller. In addition, however, a model object may observe other model objects (usually to determine when a dependent value changes) or even itself (again to determine when a dependent value changes).