Objective-C 之 NSNotificationCenter vs delegate vs KVO

 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.

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值