iOS 关于NSNotificationCenter

通常我们在 iOS 中发生什么事件时该做什么是由 Delegate 实现的,  Apple 还为我们提供了另一种通知响应方式,那就是 NSNotification.

NSNotificationCenter 较之于 Delegate 可以实现更大的跨度的通信机制,可以为两个无引用关系的两个对象进行通信。NSNotificationCenter 的通信原理使用了观察者模式(KVO):三步骤  1在需要实施的地方注册  2并 写好触发的事件  3在需要触发该事件的地方激发

1. NSNotificationCenter 注册观察者对某个事件(以字符串命名)感兴趣,及该事件触发时该执行的 Selector 或 Block
2. NSNotificationCenter 在某个时机激发事件(以字符串命名)
3. 观察者在收到感兴趣的事件时,执行相应的 Selector 或 Block
4. 注销观察者 这个对应注册 一般在selector方法里 ,也相对于注册的时机 一般是 viewWillappear 注册 viewWillDisapper 注销
//
//  SecondViewController.m
//  StoryBoard
//
//  Created by HF on 15/1/12.
//  Copyright (c) 2015年 YLYL. All rights reserved.
//

#import "SecondViewController.h"
#import "BasicFunctuin.h"
@interface SecondViewController ()

@end

@implementation SecondViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //注册通知 通知实施方法是update  激活关键字是 @"update"
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(update) name:@"update" object:nil];
}
//触发方法
-(void) update { DLog(@"KVO");

     //观察者注销,移除消息观察者

      [[NSNotificationCenter defaultCenter]removeObserver:self name:@"update" object:nil];

}
@end
//
//  FirstViewController.m
//  StoryBoard
//
//  Created by wzyb on 14-12-11.
//  Copyright (c) 2014年 YLYL. All rights reserved.
//
#import "FirstViewController.h"
@interface FirstViewController ()

@end

@implementation FirstViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}
 
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
//实施通知 在此时触发关键字@"update" 的通知方法 只要是该关键字 方法都执行 [[NSNotificationCenter defaultCenter] postNotificationName:
@"update" object:nil]; } @end
虽然在 IOS 用上 ARC 后,不显示移除 NSNotification Observer 也不会出错,但是这是一个很不好的习惯,不利于性能和内存。

  移除通知:removeObserver:和removeObserver:name:object:其中,removeObserver:是删除通知中心保存的调度表一个观察者的所有入口,而removeObserver:name:object:   是删除匹配了通知中心保存的调度表中观察者的一个入口。

这个比较简单,直接调用该方法就行。例如:


[[NSNotificationCenter defaultCenter] removeObserver:observer name:nil object:self];


注意参数notificationObserver为要删除的观察者,一定不能置为nil。


注销观察者有2个方法:

a. 最优的方法,在 UIViewController.m 中:

-(void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
现在arc中一般post b. 单个移除: [[NSNotificationCenter defaultCenter] removeObserver:self name:
@"Notification_GetUserProfileSuccess" object:nil];
原文地址:https://www.cnblogs.com/someonelikeyou/p/4222352.html