NSNotificationCenter事件是同步还是异步接收的?

Mun*_*a89 36 nsnotificationcenter ios

如果一个类注册NSNotificationCenter某种类型的事件而另一个类发布该类型的事件,那么接收器中的代码是否会在发布类继续之前(同步)或之后(异步)执行?

- (void)poster {
    [[NSNotificationCenter defaultCenter]
        postNotificationWithName:@"myevent"
        object:nil];
    NSLog(@"Hello from poster");
}

- (void)receiver {
    [[NSNotificationCenter defaultCenter]
        addObserver:self
        selector:@selector:(mySelector)
        name:@"myevent"
        object:nil];
}

- (void) mySelector:(NSNotification *) notification {
    NSLog(@"Hello from receiver");
}
Run Code Online (Sandbox Code Playgroud)

在上面的代码示例中,"Hello from receiver"会在"Hello from caller"之前或之后打印吗?

Nis*_*agi 81

如NSNotificationCenter NSNotificationCenter的文档中所述,类参考通知是同步发布的.

通知中心同步向观察者发送通知.换句话说,postNotification:方法在所有观察者都收到并处理通知之前不会返回.要异步发送通知,请使用NSNotificationQueue.

在多线程应用程序中,通知始终在发布通知的线程中传递,这可能与观察者注册自己的线程不同.

希望它能帮到你.

  • 简短而恰当的答案!! (3认同)