NSNotificationCenter通知中心是同步操作还是异步操作

时间:2021-06-14 23:30:47

题目

通知中心是同步操作还是异步操作?

代码实现

- (void)viewDidLoad
{
[super viewDidLoad];

self.btn = [UIButton buttonWithType:UIButtonTypeCustom];

CGFloat x,y,w,h;
x = 100;
y = 100;
w = 100;
h = 100;

self.btn.frame = (CGRect){x,y,w,h};
self.btn.backgroundColor = [UIColor redColor];
[self.view addSubview:self.btn];

[self.btn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dosth) name:@"click" object:nil];

}
- (void)dosth
{

//同步
NSLog(@"收到通知");
sleep(3);
NSLog(@"处理通知完毕");

//异步
/*
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSLog(@"收到通知");
sleep(3);
NSLog(@"异步-处理通知完毕");
}
)
;
*/
}
-(void)btnClick
{
//同步
NSLog(@"开始");
[[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:@"click" object:nil userInfo:nil]];
NSLog(@"结束");

//异步
/*
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSLog(@"异步-开始");
[[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:@"click" object:nil userInfo:nil]];
NSLog(@"异步-结束");
});
*/
}

可以在post地方打个断点,会发现通知中心是同步的。

当然也可以做成异步处理。