发送NSNotification的时候是同步机制,接受通知的方法执行完成后才会向下运行。示例代码如下:
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(logOne) name:@"notificationOne"object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(logTwo) name:@"notificationTwo"object:nil];
NSLog(@"notificationOne b");
[NSThread detachNewThreadSelector:@selector(notificationOne) toTarget:self withObject:nil];
NSLog(@"notificationOne e");
sleep(1);
NSLog(@"notificationTwo b");
[NSThread detachNewThreadSelector:@selector(notificationTwo) toTarget:self withObject:nil];
NSLog(@"notificationTwo e");
// Do any additional setup after loading the view, typically from a nib.
}
-(void)notificationOne{
[[NSNotificationCenter defaultCenter] postNotificationName:@"notificationOne" object:nil];
}
-(void)notificationTwo{
[[NSNotificationCenter defaultCenter] postNotificationName:@"notificationTwo" object:nil];
}
-(void)logOne{
NSLog(@"logOne b");
sleep(10);
NSLog(@"logOne e");
}
-(void)logTwo{
NSLog(@"logTwo b");
sleep(1);
NSLog(@"logTwo e");
}
2016-07-01 11:56:11.789 NotificationPostTest[854:20877] notificationOne b
2016-07-01 11:56:11.790 NotificationPostTest[854:20877] notificationOne e
2016-07-01 11:56:11.790 NotificationPostTest[854:20960] logOne b
2016-07-01 11:56:12.791 NotificationPostTest[854:20877] notificationTwo b
2016-07-01 11:56:12.792 NotificationPostTest[854:20877] notificationTwo e
2016-07-01 11:56:12.792 NotificationPostTest[854:20966] logTwo b
2016-07-01 11:56:13.797 NotificationPostTest[854:20966] logTwo e
2016-07-01 11:56:21.793 NotificationPostTest[854:20960] logOne e