[消息传递之五]-NSMatchPort练习
2016-01-10 10:55
190 查看
#import <UIKit/UIKit.h> @interface ViewController : UIViewController<NSMachPortDelegate> @property (nonatomic) NSMutableArray* NotArray; @property (nonatomic) NSLock* NotLock; @property (nonatomic) NSMachPort* NotPort; @end
#import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; self.NotArray = [[NSMutableArray alloc] init]; self.NotLock = [[NSLock alloc] init]; self.NotPort = [[NSMachPort alloc] init]; self.NotPort.delegate = self; //注意点1:kCFRunLoopCommonModes 将输入源加入此模式意味着在Common Modes中包含的所有模式下都可以处理 //注意点2:NSRunLoop主要是用于oc程序,而CFRunLoop主要用于C/C++程序,这是因为C/C++程序无法使用oc对象而创建的一个类 //注意点3:所有线程都自动创建一个RunLoop, 在线程内通过 [NSRunLoop currentRunLoop] 获得当前线程的RunLoop. [[NSRunLoop currentRunLoop] addPort:self.NotPort forMode:NSDefaultRunLoopMode]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ProcessNotification:) name:@"ObserverName" object:nil]; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSMutableDictionary* dic = [[NSMutableDictionary alloc] init]; [dic setObject:[NSNumber numberWithInteger:80] forKey:@"param1"]; [[NSNotificationCenter defaultCenter] postNotificationName:@"ObserverName" object:self userInfo:dic]; }); } -(void)handleMachMessage:(void *)msg { [self.NotLock lock]; //msg应该是NSPortMessage*但NSPortMessage* m = (__bridge NSPortMessage*)msg;这样写不可以,不清楚原因。 NSNotification* ns= [self.NotArray objectAtIndex:0]; while ([self.NotArray count]) { [self.NotArray removeObjectAtIndex:0]; [self.NotLock unlock]; [self ProcessNotification:ns]; [self.NotLock lock]; } [self.NotLock unlock]; } -(void) ProcessNotification:(NSNotification*) Notification { NSLog(@"%@",[NSThread currentThread]); NSLog(@"%@",[Notification userInfo]); if ([NSThread currentThread] != [NSThread mainThread]) { [self.NotLock lock]; [self.NotArray addObject:Notification]; [self.NotLock unlock]; //sendBeforeDate 函数没理解怎么使用,也许这几个参数就是NSPortMessage的组成部分,哎~~ [self.NotPort sendBeforeDate:[NSDate date] components:nil from:0 reserved:100]; }; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end1,实现了用指定线程处理了通知notification.
2,这个方式如果找不到指定的线程(port线程和发起notification的线程),那么就进入了死循环,后果很严重。
3,nsrunloop与自定义的main,有无联系,现在还没有弄清楚,哎~~
相关文章推荐
- AD 中常用快捷键 6.9版本
- Reflector 已经out了,试试ILSpy
- JavaScript 基础
- Catia二次开发R19安装说明
- 机器学习与数据挖掘网上资源搜罗——良心推荐
- 【ASP.NET】母版页与include
- linux网络设备驱动(二)
- 为什么程序猿比程序媛多?
- Eclipse常用快捷键和Linux命令大全
- java对文件压缩与解压缩操作
- 二分查找大集合(妈妈再也不用担心我的二分查找了)
- Android service binder aidl 关系
- 码农动手换雨刮条
- C/C++文件操作2——fstream类
- LeetCode:219. Contains Duplicate II
- Git常用命令
- Python之import流程
- redis初步入门
- EXT3.0在IE下Range不兼容解决办法
- ecshop 去版权(前台)