NSNotificationCenter NSNotificationQueue 同步?异步?
刚同事问一个问题,想起了一道面试题目,说是通知发送接受过程是同步还是异步。记得是同步,写个demo证实下
#import "NotificationViewController.h"
#define NOTIFICATIONNAME @"NSNotificationCenter__"
@interface NotificationViewController ()
@end
@implementation NotificationViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
button.frame = CGRectMake(0, 0, 100, 100);
button.backgroundColor = [UIColor redColor];
[button addTarget:self action:@selector(buttonClick) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addObserver) name:NOTIFICATIONNAME object:nil];
}
- (void)buttonClick {
NSLog(@"开始postNotificationName==%@",[[NSThread currentThread]description]);
[[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATIONNAME object:nil];
NSLog(@"结束postNotificationName==%@",[[NSThread currentThread]description]);
}
- (void)addObserver
{
NSLog(@"接收到消息==%@",[[NSThread currentThread]description]);
NSLog(@"睡眠5秒");
sleep(5);
}
@end
结果验证了是同步的
开始postNotificationName==<NSThread: 0x600002b84680>{number = 1, name = main}
接收到消息==<NSThread: 0x600002b84680>{number = 1, name = main}
睡眠5秒
结束postNotificationName==<NSThread: 0x600002b84680>{number = 1, name = main}
如果不想同步等待呢,除了另起一个线程,还有一个NSNotificationQueue可以来实现
#import "NotificationViewController.h"
#define NOTIFICATIONNAME @"NSNotificationCenter__"
@interface NotificationViewController ()
@end
@implementation NotificationViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIButton *button1 = [UIButton buttonWithType:UIButtonTypeSystem];
button1.frame = CGRectMake(200, 0, 100, 100);
button1.backgroundColor = [UIColor redColor];
[button1 addTarget:self action:@selector(buttonClick1) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button1];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addObserver) name:NOTIFICATIONNAME object:nil];
}
- (void)addObserver
{
NSLog(@"接收到消息==%@",[[NSThread currentThread]description]);
NSLog(@"睡眠5秒");
sleep(5);
}
- (void)buttonClick1
{
NSLog(@"开始postNotificationName==%@",[[NSThread currentThread]description]);
NSNotification *noti = [NSNotification notificationWithName:NOTIFICATIONNAME object:nil];
[[NSNotificationQueue defaultQueue] enqueueNotification:noti postingStyle:NSPostASAP];
//这里有同步异步参数,NSPostASAP,NSPostNow
NSLog(@"结束postNotificationName==%@",[[NSThread currentThread]description]);
}
@end
开始postNotificationName==<NSThread: 0x600002b84680>{number = 1, name = main}
结束postNotificationName==<NSThread: 0x600002b84680>{number = 1, name = main}
接收到消息==<NSThread: 0x600002b84680>{number = 1, name = main}
睡眠5秒