NSNotificationCenter NSNotificationQueue 同步?異步赎瞎?
剛同事問一個(gè)問題牌里,想起了一道面試題目,說是通知發(fā)送接受過程是同步還是異步务甥。記得是同步牡辽,寫個(gè)demo證實(shí)下
#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(@"結(jié)束postNotificationName==%@",[[NSThread currentThread]description]);
}
- (void)addObserver
{
NSLog(@"接收到消息==%@",[[NSThread currentThread]description]);
NSLog(@"睡眠5秒");
sleep(5);
}
@end
結(jié)果驗(yàn)證了是同步的
開始postNotificationName==<NSThread: 0x600002b84680>{number = 1, name = main}
接收到消息==<NSThread: 0x600002b84680>{number = 1, name = main}
睡眠5秒
結(jié)束postNotificationName==<NSThread: 0x600002b84680>{number = 1, name = main}
如果不想同步等待呢,除了另起一個(gè)線程敞临,還有一個(gè)NSNotificationQueue可以來實(shí)現(xiàn)
#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];
//這里有同步異步參數(shù)奏黑,NSPostASAP编矾,NSPostNow
NSLog(@"結(jié)束postNotificationName==%@",[[NSThread currentThread]description]);
}
@end
開始postNotificationName==<NSThread: 0x600002b84680>{number = 1, name = main}
結(jié)束postNotificationName==<NSThread: 0x600002b84680>{number = 1, name = main}
接收到消息==<NSThread: 0x600002b84680>{number = 1, name = main}
睡眠5秒