美文网首页
Object -C 通知 &线程的注意点

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

作者: 哔哩哔哩智能喵 | 来源:发表于2017-01-03 17:00 被阅读13次
    • 通知注意点:

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

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

        • 第一种是由观察者去监听通知,然后调用观察者的方法,需要观察者对象。
        • 第二种是让系统去监听通知,需要用到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
    

    相关文章

      网友评论

          本文标题:Object -C 通知 &线程的注意点

          本文链接:https://www.haomeiwen.com/subject/hqdnvttx.html