NSNotificationCenter的同步和异步
来源:互联网 发布:金域名都南昌 编辑:程序博客网 时间:2024/06/05 23:08
首先上代码:
- (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
异步处理:
方法一:
让通知事件处理方法在子线程中执行,例如:
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
通过这里的时间间隔可以看出, 通过通知队列来管理通知,不会再造成阻塞。
1 0
- NSNotificationCenter的同步和异步
- NSNotificationCenter同步异步的问题
- 同步和异步的区别
- 同步和异步的区别
- 同步和异步的区别
- 同步和异步的区别
- 同步和异步的区别
- 同步和异步的区别
- 同步和异步的理解
- 同步和异步的区别
- 同步和异步的区别
- 同步和异步的区别
- 同步和异步的区别
- Ajax的异步和同步
- 同步和异步的区别
- 同步和异步的区别
- 同步和异步的区别
- 异步和同步的概念
- js转到jsp参数传递
- 防止疲劳和忧虑的第一原则
- linux下cat命令简略
- Linux-vim
- python中if __name__ == '__main__': 的解析
- NSNotificationCenter的同步和异步
- ext中的一些用法心得
- Sicily 2302. Queue Implementation Using a Circular
- STL之partition和stable_partition
- ListView 的优化及使用
- ios target-action响应方法的不同形式
- cocos2d 中使用jni C++ 调用 Java 方法
- NodeJS+Express模块的跨域访问控制问题
- linux tar.gz zip 解压缩 压缩命令