IOS学习之 NSNotificationCenter消息通信机制介绍

来源:互联网 发布:centos 软件选择 编辑:程序博客网 时间:2024/05/16 17:03

作用:NSNotificationCenter是专门供程序中不同类间的消息通信而设置的.

注册通知:即要在什么地方接受消息

             [[NSNotificationCenter defaultCenter]addObserver:selfselector:@selector(mytest:)name:@" mytest"object:nil];

      参数介绍:

addObserver: 观察者,即在什么地方接收通知;

       selector: 收到通知后调用何种方法;

        name: 通知的名字,也是通知的唯一标示,编译器就通过这个找到通知的。

发送通知:调用观察者处的方法。

         [[NSNotificationCenter defaultCenter] postNotificationName:@"mytest" object:searchFriendArray];

          参数:

         postNotificationName:通知的名字,也是通知的唯一标示,编译器就通过这个找到通知的。

                 object:传递的参数

注册方法的写法:

- (void) mytest:(NSNotification*) notification

{

   id obj = [notification object];//获取到传递的对象

}

 

对象之间进行通信最基本的方式就是消息传递,在Cocoa中提供Notification Center机制来完成这一任务。其主要作用就是负责在任意两个对象之间进行通信。使用方法很简单,如下几个步骤即可:

A与B之间进行通信,B来触发事件,A接受该事件,并作出响应。
1) A编写自定义
的消息响应函数update
2) A向消息中心注册,[NSNotificationCenter defaultCenter] addObserver: self selector:@selector(update) name:@"update" object:nil]
3) B触发事件[[NSNotificationCenter defaultCenter] postNotificationName:@"update" object:nil]

每一个进程都有一个默认的 NSNotificationCenter,可以通过类方法defaultCenter获取该消息中心的实例。消息中心可以处理同一进程中不同对象之间的 消息。如果要在同一台机器上进行进程间的通信,需要使用NSDistributedNotificationCenter。

消息中心以同步的方式将消息分发到所有的观察者中,换言之,直到所有的观察者都收到消息并处理完毕以后,控制权才会回到调用者的手里。如果需要异步的处理消息,需要使用通知队列NSNotificationQueue。

在多线程程序中,通知会被分发到每一个发起消息的线程中,这可能与观察者注册时所在的线程已经不是同一线程。

1.定义消息创建的关联值 也就是找到方法的标志

NSString *constGameToIPhoneNotification =@"GameToIPhoneNotification";GameToIPhoneNotification变量,@"GameToIPhoneNotification"这个值存于通知中心中,信息中心通过这个值来识别变量

1.注册一个消息中心

NSNotificationCenter*center = [NSNotificationCenterdefaultCenter];

[centeraddObserver:selfselector:@selector(onToIphone:)name:GameToIPhoneNotificationobject:nil];

-(void)onToIphone:(NSNotification*)notify :这个方法是接受到GameToIPhoneNotification这个通知所调用的方法

2.调用信息

NSNotificationCenter * center = [NSNotificationCenter defaultCenter];

[center postNotificationName:GameToIPhoneNotification object:niluserInfo:[NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt:SMSRecommendNotification] ,@"actcode",nil]];

[NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt:SMSRecommendNotification] 这个是传递给-(void)onToIphone:(NSNotification*)notify 的参数。

0 0