iOS基础知识整理之Notification Center

Notification Center

概念

通过通知中心向所有注册观察者广播的信息容器
它是一个单例对象,允许当事情发生时通知一些对象,让对象作出相应反应。
它允许我们在低程度耦合的情况下,满足控制器与一个任意的对象进行通信的目的。
这种模式的基本特征是为了让其他的对象能够接收到某种事件传递过来的通知,主要使用通知名称来发送和接收通知。
基本上不用考虑其他影响因素,只需要使用同样的通知名称,监听该通知的对象(即观察者)再对通知做出反应即可。

优缺点

1.优点

  • 代码简短,实现简单;

  • 对于一个发出的通知,多个对象能够做出反应,简单实现一对多的方式,较之于Delegate可以实现更大跨度的通信机制;

  • 能够通过object和userInfo传递参数,object和userInfo可以携带发送通知时传递的信息。

2.缺点

  • 在编译期间不会检查通知是否能够被观察者正确处理;

  • 在释放通知的观察者时,需要在通知中心移除观察者;

  • 在调试的时候通知传递的过程很难控制和跟踪;

  • 发送通知和接收通知的时候必须保持通知名称一致;

  • 通知发出后,不能从观察者获得任何反馈信息。

使用方式

1.不传参数

发送通知

1
2

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

监听

1
2

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

调用方法

1
2

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

2.使用object传递参数

发送通知

1
2
3
4

NSString *object = @"notiObject";

[[NSNotificationCenter defaultCenter] postNotificationName:@"notificationWithObject" object:object];

监听

1
2

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

调用方法

1
2
3
4
5
6
7
8

- (void)notiWithObject:(NSNotification *)notiication {

id object = notiication.object;

NSLog(@"Received the notification with object");

}

3.使用userInfo传递参数

发送通知

1
2
3
4

NSDictionary *userInfoDict = @{@"userInfo":@"130293739"};

[[NSNotificationCenter defaultCenter] postNotificationName:@"notificationWithUserInfo" object:nil userInfo:userInfoDict];

监听

1
2

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

调用方法

1
2
3
4
5
6
7
8

- (void)notiWithUserInfo:(NSNotification *)notiication {

NSDictionary *userInfo = notiication.userInfo;

NSLog(@"Received the notification with userInfo:%@",userInfo);

}