NSPort 和 RunLoop 消息发送

NSPort与NSRunloop的关系是流与消息调度的关系。

NSPort 将流插入到消息调度队列;

相当于 Socket将流插入到应用一样

- (void)launchThread {

    NSPort *myport = [NSMachPort port];

    if(myport) {

        //让本类持有即将到来的端口消息。

        [myport setDelegate:self];

        //将port添加到当前的runloop

        [[NSRunLoop currentRunLoop] addPort:myport forMode:NSDefaultRunLoopMode];

        //当前线程调起工作线程

        [NSThread detachNewThreadSelector:@selector(LaunchThreadWithPort:) toTarget:[MyWorkerClass new] withObject:myport];

    }

}

 

#pragma mark - port delegate 

 

#define kCheckinMessage 1002233

 

- (void)handlePortMessage:(NSPortMessage *)message {

    NSLog(@"接收到子线程额消息");

    //消息的id

    uint32_t messageID = message.msgid;

    //获取远程端口,也就是工作线程的端口。线程通信需要两个端口??

    /*

     * 本地线程和远程线程可以使用相同的端口对象进行“单边通信”,(换句话说)一个线程创建的“本地端口对象”成为另一个线程的“远程端口对象”。

     *

     */

    NSPort *distanPort = nil;

    if(messageID == kCheckinMessage) {

        //获取工作线程关联的端口

        distanPort = message.sendPort;

    }

    NSLog(@"工作线程的port===%@",distanPort);

}

 

- (void)LaunchThreadWithPort:(id)port {

    //

    [[NSThread currentThread] setName:@"HaoyuWorkerThread"];

    //设置当前线程和主线程通信的端口

    NSPort *distantPort = (NSPort *)port;

    //初始化当前当前类的对象

    //MyWorkerClass *work = [MyWorkerClass new];

    //给主线程发送消息

    [self sendMessageToOtherThread:distantPort];

    //启动当前线程的runloop

    [[NSRunLoop currentRunLoop] run];

}

 

//private method

- (void)sendMessageToOtherThread:(NSPort *)outPort {

    self.remotePort = outPort;

    //创建工作线程自己的端口并绑定工作线程

    NSPort* myPort = [NSMachPort port];

    [myPort setDelegate:self];

    [[NSRunLoop currentRunLoop] addPort:myPort forMode:NSDefaultRunLoopMode];

   //创建签到消息

    NSPortMessage *messageObjc = [[NSPortMessage alloc] initWithSendPort:outPort receivePort:myPort components:@[@"aa",@"bb"]];

    

    if(messageObjc) {

        uint32_t kCheckinMessage = 1002233;

        [messageObjc setMsgid:kCheckinMessage];

        BOOL sendSuccess = [messageObjc sendBeforeDate:[NSDate date]];

        if(sendSuccess) {
            NSLog(@"发送成功");
        }
    }
}

 
#pragma mark - delegate 
- (void)handlePortMessage:(NSPortMessage *)message {

    NSLog(@"接收到父线程的消息");

}

转自https://www.cnblogs.com/feng9exe/p/8867475.html

你可能感兴趣的:(NSPort 和 RunLoop 消息发送)