預設的通知是同步的:
代碼如下:
-(void)viewDidLoad {
[super viewDidLoad]; //註冊通知觀察者 [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(comeTrueNotification:) name:kNotificationName object:@"wow"]; UIButton *sendNoticeBtn = [UIButton buttonWithType:UIButtonTypeSystem]; [sendNoticeBtn setFrame:CGRectMake(100, 100, 100, 100)]; [sendNoticeBtn setBackgroundColor:[UIColor cyanColor]]; [sendNoticeBtn setTitle:@"sendBtn" forState:UIControlStateNormal]; [self.view addSubview:sendNoticeBtn]; [sendNoticeBtn addTarget:self action:@selector(sendNoticeBtnDown) forControlEvents:UIControlEventTouchUpInside]; NSLog(@"%d,%@,viewDidLoad",__LINE__,[NSThread currentThread]);
}
-(void)comeTrueNotification:(NSNotification *)notification {
NSString *message = notification.object; //執行訊息方法 NSLog(@"%d,%@,%@",__LINE__,[NSThread currentThread],message); sleep(5); NSLog(@"%d,%@,comeTrueNotification",__LINE__,[NSThread mainThread]);
}
-(void)sendNoticeBtnDown {
//發送訊息 [[NSNotificationCenter defaultCenter]postNotificationName:kNotificationName object:@"wow"]; NSLog(@"%d,%@,sendNoticeBtnDown",__LINE__,[NSThread currentThread]);
}
運行結果:
控制台展示.png
可以參考好文:NSNotificationCenter的同步和非同步