iOS NSNotificationCenter(消息机制)

转自:http://blog.csdn.net/liliangchw/article/details/8276803

对象之间进行通信最基本的方式就是消息传递,在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 的参数。

iOS开发之NSNotificationCenter(通知)的使用方法

iOS软件开发的时候会遇到这种情况:打开APP后会在后台运行某个方法,例如下载文件,下载完成后可能需要调用某个方法来刷新界面,这时候可能没法在下载的函数中回调。NSNotificationCenter(通知)是一个很好的选择。

通知使用起来非常的简单:
1. 定义将要调用的方法:

- (void)callBack{
    NSLog(@"this is Notification.");
}

2. 定义通知:

[[NSNotificationCenter defaultCenter] addObserver: self
    selector: @selector(callBack)
    name: @"back"
    object: nil];

3. 调用通知:

- (void)getNotofocation{
    NSLog(@"get it.");
    //发出通知
    [[NSNotificationCenter defaultCenter] postNotificationName:@"back" object:self];
}
4. 移出通知:
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"back" object:nil];
    [super dealloc];
}
原文地址:https://www.cnblogs.com/741162830qq/p/4557448.html