测试iOS的Notification是同步还是异步

面试被问到这个问题,不是很清楚,写代码测试并记录一下。

#pragma mark - 测试通知
-(void)testNotification
{
    // 初始化一个按钮
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(100, 100, 100, 50)];
    button.backgroundColor = [UIColor orangeColor];
    [button setTitle:@"触发通知" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonDown) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    
    // 注册通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(actionNotification:)
                                                 name:kNotificationName
                                               object:nil];
}
- (void) actionNotification: (NSNotification*)notification
{
    NSString* message = notification.object;
    NSLog(@"message:%@",message);
    
    sleep(3);   // 睡3秒
    NSLog(@"通知说话结束");
}

- (void)buttonDown
{
    [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationName object:@"通知说话开始"];
    NSLog(@"按钮说话");
}

点击触发通知按钮后,控制台打印如下:

通过这里的时间间隔可以看出,通知的过程是同步进行的。

在抛出通知以后,观察者在通知事件处理完成以后(这里我们休眠3秒),抛出者才会往下继续执行,也就是说这个过程默认是同步的;当发送通知时,通知中心会一直等待所有的observer都收到并且处理了通知才会返回到poster;

PS:

如果想改同步为异步,也是有办法的。比如让通知事件处理方法在子线程中执行。

- (void) actionNotification: (NSNotification*)notification
{
//    NSString* message = notification.object;
//    NSLog(@"message:%@",message);
//
//    sleep(3);   // 睡3秒
//    NSLog(@"通知说话结束");
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSString* message = notification.object;
        NSLog(@"message:%@",message);
        
        sleep(3);
        
        NSLog(@"通知说话结束:%@",[NSThread currentThread]);
        
    });
}

- (void)buttonDown
{
    [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationName object:@"通知说话开始"];
    NSLog(@"按钮说话:%@",[NSThread currentThread]);
}

此时点击触发通知按钮,控制台打印输入:

猜你喜欢

转载自www.cnblogs.com/gwfeng/p/8964846.html
今日推荐