首先上代码:
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; [button setFrame:CGRectMake(0, 0, 400, 60)]; [button addTarget:self action:@selector(buttonDown) forControlEvents:UIControlEventTouchUpInside]; [button setTitle:@"Post Notification" forState:UIControlStateNormal]; [self.view addSubview:button]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(actionNotification:) name:kNotificationName object:nil]; } - (void) actionNotification: (NSNotification*)notification { NSString* message = notification.object; NSLog(@"%@",message); sleep(5); NSLog(@"Action Notification Finish"); } - (void)buttonDown { [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationName object:@"object"]; NSLog(@"buttonDown"); }
点击button以后,打印信息如下:
2015-03-17 17:17:59.285 AppTest[16470:169797] object
2015-03-17 17:18:04.285 AppTest[16470:169797] Action Notification
Finish
2015-03-17 17:18:04.286 AppTest[16470:169797] buttonDown
通过这里的时间间隔可以看出,在抛出通知以后,观察者在通知事件处理完成以后(这里我们休眠5秒),抛出者才会往下继续执行,也就是说这个过程默认是同步的;当发送通知时,通知中心会一直等待所有的observer都收到并且处理了通知才会返回到poster;
异步处理:
方法一:
让通知事件处理方法在子线程中执行,例如:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ sleep(5); });
就不会造成阻塞;
方法二:
您可以通过NSNotificationQueue
的enqueueNotification:postingStyle:
和enqueueNotification:postingStyle:coalesceMask:forModes:
方法将通告放入队列,实现异步发送,在把通告放入队列之后,这些方法会立即将控制权返回给调用对象。
我们修改button事件如下:
- (void)buttonDown { NSNotification *notification = [NSNotification notificationWithName:kNotificationName object:@"object"]; [[NSNotificationQueue defaultQueue] enqueueNotification:notification postingStyle:NSPostASAP]; // [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationName object:@"object"]; NSLog(@"buttonDown"); }
点击button以后,打印信息如下:
2015-03-17 18:22:05.619 AppTest[18557:195583] buttonDown
2015-03-17 18:22:05.636 AppTest[18557:195583] object
2015-03-17 18:22:10.641 AppTest[18557:195583] Action Notification Finish
通过这里的时间间隔可以看出, 通过通知队列来管理通知,不会再造成阻塞。