前言
作为iOS开发者,大家应该都使用过系统通知(NSNotificationCenter),无非就是三步,1. 注册通知,2.发送通知,3.销毁观察者,我在这里就不多解释了;。如果忘记销毁观察者,ios9之前是会崩溃的。因此我就有了自己实现全局一对多分发通知的想法,于是封装了PSSNotificationCenter
系统通知如何使用
通知的使用为3步:
- 注册通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveSysNoti) name:@"target" object:nil];
- (void)receiveSysNoti:(NSNotification *)noti {
NSLog(@"%@", [[NSThread currentThread] isMainThread] ? @"收到系统通知:主线程" : @"收到系统通知:子线程");
}
- 在需要的时候发送通知
[[NSNotificationCenter defaultCenter] postNotificationName:@"target" object:nil];
- 移出观察者
如果iOS9之前,不移除观察者是会崩溃的,而且崩溃不会有断点,如果你继承了友盟,甚至不会给你打印崩溃信息,很难找,所以务必要记得。
// 移除目标所有通知
[[NSNotificationCenter defaultCenter] removeObserver:self];
// 移除目标对应通知
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"target" object:nil];
系统通知还可以使用block的方式:
但是使用block方式会有内存问题,即便用上面两个方法移除,block本身依旧被NotificationCenter持有,当发送通知时依然会运行;请看代码
// 注册通知
[[NSNotificationCen