iOS中NSNotification是同步还是异步的?

前几天朋友问我这样一个问题,稍微记录下。

答案是同步的。

- (void)viewDidLoad {
    [super viewDidLoad];

    // 初始化一个按钮
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(50, 50, 50, 50)];
    button.backgroundColor = [UIColor cyanColor];
    [button setTitle:@"按钮" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];

    // 注册通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(buttonActionNotification:)
                                                 name:@"testNotificationOne"
                                               object:nil];

}

- (void) buttonActionNotification: (NSNotification*)notification
{
    NSString* str = notification.object;
    NSLog(@"%@",str);

    sleep(2);

    NSLog(@"任务结束");
}

- (void) buttonAction
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"testNotificationOne" object:@"任务开始"];

    NSLog(@"事件开始");
}


执行结果为:  任务开始--->  任务结束---> 事件开始

因为 NSNotificationCenter 会一直等待所有的 接收者 (observer)都收到并且处理了通知才会返回到poster 
才会执行例子中buttonAction后面的事件开始

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容