iOS 通知中心 NSNotificationCenter

iOS开发中,每个app都有一个通知中心,通知中心可以发送和接收通知。

在使用通知中心 NSNotificationCenter之前,先了解一下通知 NSNotification。

NSNotification 可以理解为消息对象,包含三个成员变量,如下: 

@property (readonly, copy) NSString *name;
@property (nullable, readonly, retain) id object;
@property (nullable, readonly, copy) NSDictionary *userInfo;

name:通知的名称

object:针对某一个对象的通知

userInfo:字典类型,主要是用来传递参数

创建并初始化一个NSNotification可以使用下面的方法:

+ (instancetype)notificationWithName:(NSString *)aName object:(nullable id)anObject;
+ (instancetype)notificationWithName:(NSString *)aName object:(nullable id)anObject userInfo:(nullable NSDictionary *)aUserInfo;

NSNotificationCenter 通知中心,是一个单例。只能使用  [NSNotificationCenter defaultCenter] 获取通知中心对象。

发送通知可以使用下面的方法:

[[NSNotificationCenter defaultCenter] postNotificationName:@"testNotification" object:nil];

或者:

NSDictionary *userInfo = @{@"name":@"John",@"age":@"15"};
NSNotification
*notice = [NSNotification notificationWithName:@"testNotification" object:nil userInfo:userInfo]; [[NSNotificationCenter defaultCenter] postNotification:notice];

添加一个观察者的方法(可以理解成在某个观察者中注册通知):

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

有四个参数:第一个参数是观察者,也就是谁注册这个通知;第二个参数是当接收到通知时的回调函数;第三个参数是通知的名称,通知名是区分各个通知的唯一标识;第四个参数是接收哪个对象发过来的通知,如果为nil,则接收任何对象发过来的该通知。

移除观察者,两种方法:

- (void)removeObserver:(id)observer;
- (void)removeObserver:(id)observer name:(NSString *)aName object:(id)anObject;

NSNotificationCenter 的使用举例如下:

发送通知(两种方法):

- (void)btnClicked
{
    //[[NSNotificationCenter defaultCenter] postNotificationName:@"testNotification" object:nil];
    
    NSDictionary *userInfo = @{@"name":@"John",@"age":@"15"};
    
    NSNotification *notice = [NSNotification notificationWithName:@"testNotification" object:nil userInfo:userInfo];
    [[NSNotificationCenter defaultCenter] postNotification:notice];
    
}

增加观察者:

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

回调函数(可以利用回调函数的参数 notification获得该通知的信息,比如name、object、参数):

- (void)haveNoti:(NSNotification *)notification
{
    NSLog(@"name = %@",[notification name]);
    
    
    NSDictionary *userInfo = [notification userInfo];
    NSLog(@"info = %@",userInfo);
}

针对某一个特定对象的通知的使用场景:

UITextField,比如说我们要监听UITextField 里面内容的变化,此时可以注册下面的通知

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(searchBarTextChange) name:UITextFieldTextDidChangeNotification object:self.searchBar];

self.searchBar 是 UITextField 类型。