Patterns in Objective-C: Observer Pattern

本文介绍了Objective-C中的观察者模式,也称为发布/订阅模式。主要原理是一个监听器通过预定义的协议注册到广播器。广播器在某个时刻通知所有监听器,调用它们的方法并传递参数,实现不同对象之间的异步消息传递。该模式常用于数据库更新通知、处理点击事件和实现关闭钩子等场景。Apple在Cocoa库中提供了名为NSNotification的观察者模式实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Patterns in Objective-C: Observer Pattern

Posted 12/14/2008 - 18:16 by David

One of the most common patterns, after the Singleton, in Java is the Observer Pattern. Also referred to as a Broadcaster/Listener or a Publish/Subscribe pattern. The basic principle is that there are two components: An Observer (or Listener) and a Subject (or Broadcaster).

The basic idea is that a listener registers with a broadcaster using some predefined protocol. At some later point, the broadcaster is told to notify all of its listeners, where it calls some function on each of its listeners and passes certain arguments along. This allows for asynchronous message passing between two different objects that don't have to know about one-another, they just have to know about the broadcaster.

Examples of where this gets used are to track database updates (i.e., listeners want to know when the database updates in specific ways), handle click events, or implement shutdown hooks.

Apple has provided an Observer Pattern in the Cocoa library called the NSNotificationCenter. There are three primary tasks that are performed with the NSNotificationCenter:

Adding a Observer
  1. [ [ NSNotificationCenter defaultCenter ] addObserver :listener selector : @selector (notify : ) name : @ "Event" object :notificationSendert ];

Here we see several components:

  • [NSNotificationCenter defaultCenter] - While one can create their own NSNotificationCenters, for most purposes it is sufficient to use the default.
  • addObserver:listener - listener is the object that will be notified by the NSNotificationCenter. For many applications the observer will "self register" with the observer, and thus the call will be addObserver:self.
  • selector:@selector(notify:) - Indicates which method should be called when the observer is notified.
  • name:@"Event" - The name of the event that will cause the NSNotificationCenter to notify the observer. It is a good practice to use an extern string constant instead of directly inserting the string.
  • object:notificationSender - The notificationSender represents the object that will post the notification. This is frequently used when the object in question needs to be released once a notification happens.

This is frequently nil, meaning that the NSNotificationCenter will not consider the sender when deciding whether to fire the event. If it is not nil, then only notifications sent from that specific object will fire the event (see below).

Note that if name is left as nil then all notifications sent by the notificationSender will fire the event.

The notify function can be any function that takes a single argument:

 

  1. - ( void )notify : ( NSNotification * )notification {
  2.         id notificationSender = [notification object ];
  3.         //do stuff
  4. }

 

Notifying the Observers
In some cases, such as when registering for events with Cocoa's built-in libraries (e.g., MPMoviePlayerController) the notification event is called by the library when a certain condition is met, for example when the movie ends.

In other cases, we will want to trigger that event:

  1. [ [ NSNotificationCenter defaultCenter ] postNotificationName : @ "Event" object :notificationSender ];

 

The components here are similar to when we added the observer above. The postNotificationName is identical to the name, and the object is the notificationSender.

Removing an Observer
When we are done with the observer, we will want to unregister it with the NSNotificationCenter:

 

  1. [ [ NSNotificationCenter defaultCenter ] removeObserver :listener name : @ "Event" object :notificationSender ];

 

The arguments here are the same as when we added the observer.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值