在这里先简单的介绍一下通知的用法
1、通知的创建与发送
在需要发送通知的界面中创建通知
(1)添加字典, 将数据包到字典中
NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:@"xx",@"name"nil];
(2)创建通知
NSNotification *notification = [NSNotification notificationWithName:@"InfoNotification" object:nil userInfo:dict];
(3)通过 通知中心 发送 通知
[[NSNotificationCenter defaultCenter] postNotification:notification];
2、通知的接收
在需要接收的控制器中注册通知监听者,将通知发送的信息接收
- (void)viewDidLoad{
[super viewDidLoad];
//获取通知中心单例对象
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center removeObserver:self name:@"loadCostPay" object:nil];
[center addObserver:self selector:@selector(loadViewNotice:) name:@"loadCostPay" object:nil];
}
- (void)loadViewNotice:(NSNotification *)notification{
//do something...
}
3、通知的移除
移除通知:removeObserver:和removeObserver:name:object:
其中,removeObserver:是删除通知中心保存的调度表一个观察者的所有入口,而removeObserver:name:object:是删除匹配了通知中心保存的调度表中观察者的一个入口。
通知在不使用了时一定要将其移除,因为它创建了之后会一直保存在内存中,只要添加了观察者并发送了通知,接收到以后就会调取通知中的方法
- (void)dealloc{
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"clear" object:self];
}
参考了Stack Overflow上的两篇文章,觉得老外在这通知上优化的要好一点,代码如下:
if (!opQ) {
opQ = [[NSOperationQueue alloc] init];
}
__block id observer = [[NSNotificationCenter defaultCenter] addObserverForName:@"loadCostPay" object:nil queue:opQ usingBlock:^(NSNotification *aNotification) {
dispatch_async(dispatch_get_main_queue(),
^{
//do something...
[[NSNotificationCenter defaultCenter] removeObserver:observer];
});
}];
参考文章链接