(1)通知的基本使用
@property (nonatomic, weak) id observe; - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { //监听通知(一定要先监听再发出通知, 否则监听不到通知) //方式一 //Observer:观察者 //selector:只要一监听到通知,就会调用观察者这个方法 //name:通知名称 //object:谁发出的通知 //[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reciveNote) name:@"note" object:nil]; //方式二 //name:通知名称 //object:谁发出的通知 //queue:决定block在哪个线程执行,nil:在发布通知的线程中执行 //usingBlock:只要监听到通知,就会执行这个block // 注意:一定要记得移除 _observe = [[NSNotificationCenter defaultCenter] addObserverForName:@"note" object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) { //只要监听到通知,就会调用 NSLog(@"%@",[NSThread currentThread]); NSLog(@"%@",self); }]; //发出通知 //name:通知名称 //object:谁发出的通知 [[NSNotificationCenter defaultCenter] postNotificationName:@"note" object:nil]; } //移除通知 //一个对象即将销毁就会调用 // - (void)dealloc { // //移除通知 // [[NSNotificationCenter defaultCenter] removeObserver:self]; //} - (void)dealloc { //移除通知 [[NSNotificationCenter defaultCenter] removeObserver:_observe]; } //监听到通知就会调用 //- (void)reciveNote { // NSLog(@"接收到通知"); //}
(2)通知在多线程中的使用
//方式一 //异步:监听通知,主线程:发出通知 - (void)viewDidLoad { [super viewDidLoad]; dispatch_async(dispatch_get_global_queue(0, 0), ^{ // 异步任务 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reciveNote) name:@"note" object:nil]; }); } - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { [[NSNotificationCenter defaultCenter] postNotificationName:@"note" object:nil]; } // 监听到通知就会调用 // 异步:监听通知,主线程:发出通知,接收通知代码在主线程 // 主线程:监听通知,异步:发出通知,接收通知代码在异步 // 总结:接收通知代码由发出通知线程决定 - (void)reciveNote { //dispatch_sync(dispatch_get_main_queue(), ^{ // //更新UI //}); NSLog(@"%@",[NSThread currentThread]); NSLog(@"接收到通知"); } //方式二 - (void)test2 { //queue:决定block在哪个线程执行,nil:在发布通知的线程中执行 //[NSOperationQueue mainQueue]:一般都是使用主队列 _observe = [[NSNotificationCenter defaultCenter] addObserverForName:@"note" object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) { NSLog(@"%@",[NSThread currentThread]); NSLog(@"%@",self); }]; }