您的位置:首页 > 移动开发 > IOS开发

iOS学习笔记之NSNotificationCenter(消息机制)

2012-12-10 10:09 567 查看
对象之间进行通信最基本的方式就是消息传递,在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 *const GameToIPhoneNotification = @"GameToIPhoneNotification"; GameToIPhoneNotification变量,@"GameToIPhoneNotification"这个值存于通知中心中,信息中心通过这个值来识别变量

1.注册一个消息中心

NSNotificationCenter *center = [NSNotificationCenter defaultCenter];

[center addObserver:self selector:@selector(onToIphone:) name:GameToIPhoneNotification object:nil];

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

2.调用信息

NSNotificationCenter * center = [NSNotificationCenter defaultCenter];

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

[NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt:SMSRecommendNotification] 这个是传递给-(void)onToIphone:(NSNotification*)notify
的参数。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: