What's the nicest way to do observer/observable in objective-c (iphone version)

There are two built-in ways of doing observation in Cocoa: Key-Value Observing and notifications. In neither system do you need to maintain or notify a collection of observers yourself; the framework will handle that for you.

Key-Value Observing (KVO) lets you observe a property of an object — including even a property that represents a collection — and be notified of changes to that property. You just need to send the object -addObserver:forKeyPath:options:context: passing the object you want to receive updates, the key path of the property (relative to the receiver) for which you want to receive updates, and the types of updates you want to receive. (There are similar methods you can use if you want to observe a property representing a collection.)

Notifications are older and heavier-weight. You register with an NSNotificationCenter — usually the default center — an object and selector pair to be passed a notification when an event occurs. The notification object itself can contain arbitrary data via its userInfo property, and you can choose to observe all notifications of a specific name rather than those that apply to a particular object.

Which should you use in any particular case? In general, if you care about changes to a specific property of a specific object, use Key-Value Observing. That's what it's designed for and it's intentionally lightweight. (Among other uses, it is the foundation on which Cocoa Bindings are built.) If you care about a change in state that isn't represented by a property, then notifications are more appropriate.

For example, to stay in sync when the user changes the name of a model object, I'd use KVO. To know when an entire object graph was saved, I'd use notifications.


http://stackoverflow.com/questions/165790/whats-the-nicest-way-to-do-observer-observable-in-objective-c-iphone-version

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值