-
(void)viewDidLoad {
[super viewDidLoad];UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; [button setFrame:CGRectMake(0, 100, 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);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
sleep(5);
});
NSLog(@"Action Notification Finish")
}
同步接收
//- (void)buttonDown{
// [[NSNotificationCenter defaultCenter] postNotificationName:@"kNotificationName" object:@"object"];
// NSLog(@"buttonDown");
//}
//异步子线程接收
- (void)buttonDown
{
NSNotification *notification = [NSNotification notificationWithName:@"kNotificationName"
object:@"object"];
[[NSNotificationQueue defaultQueue] enqueueNotification:notification
postingStyle:NSPostASAP];
//[[NSNotificationCenter defaultCenter] postNotificationName:kNotificationName object:@"object"];
NSLog(@"buttonDown");
}
通过打印我们可以看出,当我们发送通知以后,观察者在接收到值以后,我们休眠3秒,程序才会继续往下执行,也就是说这个过程默认是同步的;我认为这里面设计为同步,是考虑到这一点,那就是一个通知可能有多个监听者,采用同步的方式能够保证所有的观察者都能够对通知做出相应,不会遗漏。
异步处理:
方法一:
让通知事件处理方法在子线程中执行,例如:
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");
}
通过这里的时间间隔可以看出, 通过通知队列来管理通知,不会再造成阻塞。
网友评论