// 通知中心的第一种使用
1 必须先监听
// addObserver 添加观察者
// selector 只要监听到通知就会调用这个方法
// name 通知的名称
// object 谁发出的通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(Notification) name:@"note" object:nil];
// name 通知的名称
// object 谁发出的通知
[[NSNotificationCenter defaultCenter] postNotificationName:@"note" object:nil];
// 通知的方法
- (void)Notification
{
NSLog(@"收到通知");
}
// 通知中心的第二种使用
// name 通知的名称
// object 谁发出的通知
// queue 决定block在哪个线程中调用 传nil 在发布的线程中执行 [NSOperationQueue mainQueue]; 一般在主线程中调用
// 注意的是这个通知中心 没有添加观察者 移除的时候移除返回值
_object = [[NSNotificationCenter defaultCenter] addObserverForName:@"note" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
// 这里的block 在监听在通知时候 调用
[NSOperationQueue mainQueue];
}];
- (void)Notification
{
NSLog(@"收到通知");
}
-(void)dealloc
{
// 移除通知
[[NSNotificationCenter defaultCenter] removeObserver:_object];
}
通知中心使用注意点
通知中心的监听方法 在哪个线程执行 是由发出通知所在的线程决定的 所以在 监听的事件中 更新UI时要回到主线程中 避免监听事件在子线程中执行了
dispatch_async(dispatch_get_main_queue(), ^{
// 更新UI
});
// 全局异步队列
dispatch_sync(dispatch_get_global_queue(0, 0), ^{
});
// 主队列
dispatch_async(dispatch_get_main_queue(), ^{
// 更新UI
});
网友评论