`

NSNotificationCenter基础知识

    博客分类:
  • ios
 
阅读更多

Notification的工作机制

1.对应用程序中其他地方发生的事件(比如增加一条数据库记录)感兴趣的对象,会向通告中心(Notification Center,NSNotificationCenter类的实例)注册,从而成为该事件的监听者。在注册过程中,监听者需要指定方法供通告中心在事件发生时调用。

2.给数据库添加记录(或者类似事件)的对象给通告中心发一个通告(NSnotification的实例)。该通告对象包括识别通告的标志、发布通告的对象ID和可选的附加信息字典。

3.通告中心发送消息到每个已注册的监听者,调用监听者指定的方法会将通告传给这些监听者。

 

NSNotification对象

NSNotification包含三个属性:

name一个notification对象的name,由我们自己定义

objectpost该notification的object,也就是sender

userInfo伴随notification传递过去的数据,是一个NSDictionary

 

NSNotificationCenter中的方法

Getting the Notification Center

+ defaultCenter该方法用于获取当前程序中的center object

Managing Notification Observers

– addObserverForName:object:queue:usingBlock:

对快代码的操作,详见:http://blog.sina.com.cn/s/blog_63ced45101016cih.html

– addObserver:selector:name:object:

notificationObserver 一个对象,作为observer,不能为空。

notificationSelectorobserver接收到notificaiton后会调用的方法,该方法只能有一个参数,类似:- (void) mytest:(NSNotification*) notification

notificationNamenotification的name,center只会像该observer发送指定name的notification

notificationSender一个对象,作为sender,也就是说指定了只有改sender发送了name为上一个参数指定的notification,center才会向observer发送notification

– removeObserver:

notificationObserver 从center中删除observer,add方法调用后,要在合适的地方调用remove方法删除observer,否则如果多系调用add后,一个post会接收到多次notification

– removeObserver:name:object:

该方法与–addObserver:selector:name:object:结合起来使用

Posting Notifications

– postNotification:

    NSNotification

– postNotificationName:object:

notificationNamenotification name

notificationSender发送notification的object

– postNotificationName:object:userInfo:

notificationNamenotification name

notificationSender发送notification的object

userInfo伴随着notification发送过去的数据,是一个NSDictionary

 

 

Android中的四大组件之一Broadcast用来在手机上发送广播,无论是同一个程序中或是在其他的应用中,只要你注册接收该条广播,那么当广播发送之后,你就会收到,这种机制可以降低程序中间的耦合性,可以通过发送广播调用其他类中的东西。

 

在IOS中也有类似Broadcast的机制,其中包括NSNotificationCenter和NSDistributedNotificationCenter机制。

NSNotificationCenter。在IOS运行的每一个程序都有一个default center,不要自己创建。通过方法[NSNotificationCenter defaultCenter]可以获取center对象,center实际上是notification的dispatch table(调度表),center控制着程序中所有notification的添加、删除以及post后的响应。可以说NSNotificationCenter 是专门供一个程序中的不同类间的消息通信而设置的。

NSDistributedNotificationCenter用于在不同程序之间post和receive notification,这个跟Android的Broadcast比较相似。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics