NSNotificationCenter 的线程相关问题

2016-12-26  本文已影响52人  YGoooooooooal
  1. 写在ViewController中的注册通知,在页面pop后会自动在通知中心移除自己;写在其他对象中的注册通知,释放后不会自动移除自己,这时候会引起崩溃。
  2. Viewcontroller正确的写法应该是在willappear添加观察,在willdisappear移除自己。
  3. 发送通知的线程可能和接受通知的线程可能不是同一个线程,在接受通知时,需要单独处理。(NSNotificationCenter消息的接受线程是基于发送消息的线程的。也就是同步的,而有时候UI必须在主线程处理,不然会不响应,所以要针对处理)

eg.

//接受消息通知的回调
- (void)test
{
   if ([[NSThread currentThread] isMainThread]) {
       NSLog(@"main");
   } else {
       NSLog(@"not main");
   }
   dispatch_async(dispatch_get_main_queue(), ^{
       //do your UI
   });
 
}
 
//发送消息的线程
- (void)sendNotification
{
   dispatch_queue_t defaultQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
   dispatch_async(defaultQueue, ^{
       [[NSNotificationCenter defaultCenter] postNotificationName:@"test" object:nil];
   });
}
上一篇 下一篇

猜你喜欢

热点阅读