Object -C 通知 &线程的注意点

  • 通知注意点:

    • 通知顺序:一定是先监听,在发出。如果监听不到通知,马上想到有可能先发出通知,在监听通知

    • 监听通知的方法有两种:

      • 第一种是由观察者去监听通知,然后调用观察者的方法,需要观察者对象。
      • 第二种是让系统去监听通知,需要用到addObserverForName...queue带线程监听通知(此方法简单,实用性强)
    • 我们在监听通知的时候,如果想写的严谨一些,可以开线程去监听通知。

    异步:监听通知 主线程:发出通知 接收通知代码在主线程
    主线程:监听通知 异步:发出通知 接收通知代码在异步
    接收通知代码 由 发出通知线程决定
    注意:在接收通知代码中 可以加上主队列任务
    
    • 不管用哪种方法去监听通知,在dealloc方法中都需要移除通知

#import "ViewController.h"

@interface ViewController ()
@property(nonatomic,weak)id  observer ;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    /**
     监听通知
     ForName:通知名字
     object:谁发出的通知
     queue:决定block在哪个线程执行,nil:在发布通知的线程中执行 [NSOperationQueue mainQueue]:一般都是使用主队列
     usingBlock:block回调
     
     */
 self.observer = [[NSNotificationCenter defaultCenter]addObserverForName:@"note" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        NSLog(@"监听到通知%@---",[NSThread currentThread]);
    }];
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [[NSNotificationCenter defaultCenter] postNotificationName:@"note" object:nil];
    });
}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:_observer];
}
@end
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容