iOS通知是异步还是同步

2020-08-20  本文已影响0人  KB_MORE

答案: 同步

验证
##监听者1
@implementation KBNotificationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(log) name:noti object:nil];

}

//发送通知
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [[NSNotificationCenter defaultCenter ] postNotificationName:noti object:nil];
  NSLog(@"已经发送通知");

}

- (void)log{
    for (int i = 0; i<100; i++) {
        NSLog(@"%d",i);
    }
}

###监听者2
@implementation KBMBProgressViewController
+ (void)load{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginfo) name:noti object:nil];
}
+ (void)loginfo{
    for (int i = 0; i<100; i++) {
        NSLog(@"通知通知");
    }
}

运行结果
2020-08-20 11:06:32.314535+0800 YaYa[19326:473375] 通知通知
2020-08-20 11:06:32.314787+0800 YaYa[19326:473375] 通知通知
2020-08-20 11:06:32.315030+0800 YaYa[19326:473375] 通知通知
..............
2020-08-20 11:06:32.315269+0800 YaYa[19326:473375] 0
2020-08-20 11:06:32.315538+0800 YaYa[19326:473375] 1
...........
2020-08-20 11:06:32.316578+0800 YaYa[19326:473375] 99
2020-08-20 11:16:32.892943+0800 YaYa[19454:479703] 已经发送通知

中间for循环耗时操作, 最后输入 已经发送通知 可见等待监听者执行完说有方法之后才进行发送通知后续代码, 即说明通知是同步的

改变通知发送执行为异步

一 、GCD

  dispatch_async(dispatch_get_global_queue(0, 0), ^{
       [[NSNotificationCenter defaultCenter ] postNotificationName:noti object:nil];
  });
  NSLog(@"已经发送通知");

二、NSNotificationQueue

    NSNotificationQueue *queue = [[NSNotificationQueue alloc]initWithNotificationCenter:[NSNotificationCenter defaultCenter]];
    NSNotification *notify = [[NSNotification alloc]initWithName:noti object:nil userInfo:nil];
    [queue enqueueNotification:notify postingStyle:NSPostASAP];
  NSLog(@"已经发送通知");
上一篇 下一篇

猜你喜欢

热点阅读