[消息传递之五]-NSMatchPort练习

#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.
}

@end
1,实现了用指定线程处理了通知notification.

2,这个方式如果找不到指定的线程(port线程和发起notification的线程),那么就进入了死循环,后果很严重。

3,nsrunloop与自定义的main,有无联系,现在还没有弄清楚,哎~~

你可能感兴趣的:(ios,nsmatchport)