首先上代码:
- (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");
}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
异步处理:
方法一:
让通知事件处理方法在子线程中执行,例如:
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");
}
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
原文地址:http://blog.csdn.net/junjun150013652/article/details/44343365