NSPort线程间通信

·  阅读 61

1.初始化并设置NSPort的代理 dispatch_async(dispatch_get_global_queue(0, 0), ^{

     
@interface** ViewController ()<NSPortDelegate>


@property (nonatomic, copy) NSArray *arr;

@property (nonatomic, strong) NSPort *notificationPort;

@property (nonatomic, strong) NSThread *thread; 

@end


@implementation** ViewController


- (void*)viewDidLoad {

    [super viewDidLoad];

    self.notificationPort = [[NSMachPort alloc] init];

    [self.notificationPort setDelegate:self];

     __weak typeof(self) ws = self;

    //如果需要回调的线程在主线程, 则需要将notificationPort 添加到主线程的runloop里面
    dispatch_async(dispatch_get_global_queue(00), ^{

        NSLog(@"设置代理:%@", [NSThread currentThread]);
        [[NSRunLoop currentRunLoop] addPort:ws.notificationPort forMode:NSRunLoopCommonModes];

        [[NSRunLoop currentRunLoop] run];

    });
}

//代理方法
- (void)handlePortMessage:(NSPortMessage *)message {

    NSLog(@"接收:%@", [NSThread currentThread]);
}


//开启子线程, 发送port数据
-(void)btnClick {

    dispatch_async(dispatch_get_global_queue(0, 0), ^{

        NSLog(@"发送:%@", [NSThread currentThread]);

        [self.notificationPort sendBeforeDate:[NSDate date] components:nil from:nil reserved:0];

    });

    
    __weak typeof(self) ws = self;
    self.thread = [[NSThread alloc] initWithBlock:^{

        NSLog(@"发送:%@", [NSThread currentThread]);

        [ws.notificationPort sendBeforeDate:[NSDate date] components:nil from:nil reserved:0];

    }];

    [self.thread start];

}

复制代码

执行了btnClick方法后,具体的打印信息如下: 可以传递数据, 通过message获取, 可以自行尝试 2021-08-26 20:08:25.819417+0800 11111111111[31057:1025281] 设置代理:<NSThread: 0x7f9553a78fa0>{number = 5, name = (null)}

2021-08-26 20:08:28.025739+0800 11111111111[31057:1025278] 发送:<NSThread: 0x7f9553874c50>{number = 6, name = (null)}

2021-08-26 20:08:28.026308+0800 11111111111[31057:1025281] 接收:<NSThread: 0x7f9553a78fa0>{number = 5, name = (null)}

2021-08-26 20:08:28.025958+0800 11111111111[31057:1025308] 发送:<NSThread: 0x7f9556113970>{number = 8, name = (null)}

2021-08-26 20:08:28.026854+0800 11111111111[31057:1025281] 接收:<NSThread: 0x7f9553a78fa0>{number = 5, name = (null)}       

分类:
iOS
标签:
分类:
iOS
标签:
收藏成功!
已添加到「」, 点击更改