NSPort线程间通信实例(Xcode12.3)

NSPort,搜图片都指向了Sport

线程间通信能不用就不用
好像两辆行驶的车之间交换内容
用performSelector静好就是晴天

一、了解NSPort

  • NSPort是描述通信通道的抽象类。在两个NSPort对象之间通过- (BOOL)sendBeforeDate:(NSDate *)limitDate msgid:(NSUInteger)msgID components:(nullable NSMutableArray *)components from:(nullable NSPort *)receivePort reserved:(NSUInteger)headerSpaceReserved;发送消息和handlePortMessage:代理接受NSPortMessage对象,来实现线程(或进程或应用)之间的通信。
  • NSPort对象必须作为输入源添加到NSRunLoop对象中,来实现线程不退出。
  • NSPort有3个子类NSMachPort、NSMessagePort和NSSocketPort。
  • CFRunLoopSource中source1事件源采用port,来监听系统端口和通过内核和其他线程发送消息。

二、线程间通信思路

  1. 在主线程创建一个NSPort的实例A并添加主线程的NSRunLoop中。
  2. 再创建一个线程S将A作为参数发送到线程中。
  3. 线程中创建一个本地NSPort实例B,也添加到NSRunLoop中。
  4. 从B向A发送消息后,将线程S的runloop运行。
  5. 主线程收到线程S发送的消息。
  6. 主线程向线程S发送消息。
  7. 通过handlePortMessage:代理方法接受消息。

三、NSPort实例

网上找了很久就看到一篇关于NSPort实例的文章,然后发现现实有错误。我使用的是Xcode 12.3和iOS14SDK。
在一个VC中实现

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSLog(@"viewDidLoad thread is %@.", [NSThread currentThread]);
    
    self.myPort = [NSMachPort port];
    self.myPort.delegate = self;
    
    [[NSRunLoop currentRunLoop] addPort:self.myPort forMode:NSDefaultRunLoopMode];
    
    self.work = [[MyWorkerClass alloc] init];
    [NSThread detachNewThreadSelector:@selector(launchThreadWithPort:) toTarget:self.work withObject:self.myPort];
}
- (void)handlePortMessage:(NSMessagePort *)message
{
    NSLog(@"接受到子线程传递的消息。%@", message);
    
    NSUInteger msgId = [[message valueForKeyPath:@"msgid"] integerValue];
    NSMachPort *localPort = [message valueForKeyPath:@"localPort"];
    NSMachPort *remotePort = [message valueForKeyPath:@"remotePort"];
    NSMutableArray *componts = [message valueForKey:@"components"];
    for (NSData *data in componts) {
        NSLog(@"data is %@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    }
    
    if (msgId == kMsg1) {
        [remotePort sendBeforeDate:[NSDate date] msgid:kMsg2 components:nil from:localPort reserved:0];
    }
}

在VC的头部引入自定义线程类

#import "MyWorkerClass.h"

#define kMsg1 100
#define kMsg2 101

自定义线程类MyWorkerClass的h文件暴露方法

- (void)launchThreadWithPort:(NSPort *)port;

m文件实现

#define kMsg1 100
#define kMsg2 101

@interface MyWorkerClass () <NSMachPortDelegate>

@property (nonatomic, strong) NSPort *remotePort;
@property (nonatomic, strong) NSPort *myPort;

@end

@implementation MyWorkerClass

- (void)launchThreadWithPort:(NSPort *)port
{
    @autoreleasepool {
        self.remotePort = port;
        
        [[NSThread currentThread] setName:@"MyWorkerClass"];
        
        NSLog(@"launchThreadWithPort thread is %@.", [NSThread currentThread]);
        
        self.myPort = [NSMachPort port];
        self.myPort.delegate = self;
        
        [[NSRunLoop currentRunLoop] addPort:self.myPort forMode:NSDefaultRunLoopMode];
        
        [self sendPortMessage];
        
        [[NSRunLoop currentRunLoop] run];
    }
}

- (void)sendPortMessage
{
    NSData *data1 = [@"wang" dataUsingEncoding:NSUTF8StringEncoding];
    NSData *data2 = [@"yinan" dataUsingEncoding:NSUTF8StringEncoding];
    
    NSMutableArray *array = [[NSMutableArray alloc] initWithArray:@[@"1", @"2"]];
    [self.remotePort sendBeforeDate:[NSDate date] msgid:kMsg1 components:array from:self.myPort reserved:0];
}


- (void)handlePortMessage:(NSMessagePort *)message
{
    NSLog(@"接受到父类的消息。。。%@。", message);
}

运行打印为

MyDream[11004:357602] viewDidLoad thread is <NSThread: 0x600003820100>{number = 1, name = main}.
MyDream[11004:357779] launchThreadWithPort thread is <NSThread: 0x60000384d440>{number = 8, name = MyWorkerClass}.
MyDream[11004:357602] 接受到子线程传递的消息。<NSPortMessage: 0x600003874d80>
MyDream[11004:357602] data is wang
MyDream[11004:357602] data is yinan
MyDream[11004:357779] 接受到父类的消息。。。<NSPortMessage: 0x600003838900>。

四、注意点

1. handlePortMessage方法

查看NSMachPort的delegate属性为NSMachPortDelegate,而NSPort的delegate属性为NSPortDelegate。其中NSMachPortDelegate继承NSPortDelegate。只要实现其中一个就可以。

@protocol NSPortDelegate <NSObject>
@optional

- (void)handlePortMessage:(NSPortMessage *)message;
    // This is the delegate method that subclasses should send
    // to their delegates, unless the subclass has something
    // more specific that it wants to try to send first
@end

有一个问题是NSPortMessage是MacOS上使用了,所以在iOS上开发的时候就一直报错。最后修改为- (void)handlePortMessage:(NSMessagePort *)message,使用NSMessagePort来接受消息。

2. 子线程运行RunLoop

调用[[NSRunLoop currentRunLoop] run];的时机不同,就决定是否子线程能够通过NSPort接受到主线程的消息。也就是必须将[[NSRunLoop currentRunLoop] run];一定要放到[self sendPortMessage];之后。

3. components的类型

- (BOOL)sendBeforeDate:(NSDate *)limitDate msgid:(NSUInteger)msgID components:(nullable NSMutableArray *)components from:(nullable NSPort *)receivePort reserved:(NSUInteger)headerSpaceReserved;发送消息时进行传递参数components。
当components的内容为字符串时,报警告

2021-01-27 09:57:24.521514+0800 MyDream[10747:331651] *** D.O. message send ignoring unknown component type '__NSCFConstantString'
2021-01-27 09:57:24.522004+0800 MyDream[10747:331651] *** D.O. message send ignoring unknown component type '__NSCFConstantString'

而当components的内容为class时,报警告

2021-01-27 09:41:22.425767+0800 MyDream[10541:318874] *** D.O. message send ignoring unknown component type 'MyWorkerData'
2021-01-27 09:41:22.425931+0800 MyDream[10541:318874] *** D.O. message send ignoring unknown component type 'MyWorkerData'

一头雾水又度娘无解的时候,看到了

// The components array consists of a series of instances
    // of some subclass of NSData, and instances of some
    // subclass of NSPort; since one subclass of NSPort does
    // not necessarily know how to transport an instance of
    // another subclass of NSPort (or could do it even if it
    // knew about the other subclass), all of the instances
    // of NSPort in the components array and the 'receivePort'
    // argument MUST be of the same subclass of NSPort that
    // receives this message.  If multiple DO transports are
    // being used in the same program, this requires some care.

按苹果的注释习惯应该放在方法的上面的,这个竟然是在下方,导致一致被忽略了。尴尬尴尬。主要意思就是components需要是NSData组成。将内容修改为NSData后


components

传递参数成功。

五、performSelector实现线程间通信

NSThread中提供了

- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(nullable id)arg waitUntilDone:(BOOL)wait modes:(nullable NSArray<NSString *> *)array;
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(nullable id)arg waitUntilDone:(BOOL)wait;
    // equivalent to the first method with kCFRunLoopCommonModes

- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(nullable id)arg waitUntilDone:(BOOL)wait modes:(nullable NSArray<NSString *> *)array API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0));
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(nullable id)arg waitUntilDone:(BOOL)wait API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0));
    // equivalent to the first method with kCFRunLoopCommonModes
- (void)performSelectorInBackground:(SEL)aSelector withObject:(nullable id)arg API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0));

直接指定线程来执行方法,方便简洁。
写一个demo来show一把。将上面的修改一把,VC中的代码不用修改,MyWorkerClass的m文件修改如下:

#import "MyWorkerClass.h"

#define kMsg1 100
#define kMsg2 101

@interface MyWorkerClass () <NSMachPortDelegate>

@property (nonatomic, strong) NSPort *remotePort;
@property (nonatomic, strong) NSPort *myPort;
@property (nonatomic, strong) NSThread *thread;

@end

@implementation MyWorkerClass

- (void)launchThreadWithPort:(NSPort *)port
{
    @autoreleasepool {
        self.remotePort = port;
        
        self.thread = [NSThread currentThread];
        
        [[NSThread currentThread] setName:@"MyWorkerClass"];
        
        NSLog(@"launchThreadWithPort thread is %@.", [NSThread currentThread]);
        
        self.myPort = [NSMachPort port];
        self.myPort.delegate = self;
        
        [[NSRunLoop currentRunLoop] addPort:self.myPort forMode:NSDefaultRunLoopMode];
        
        
        [self sendPortMessage];
        
        [[NSRunLoop currentRunLoop] run];
    }
}

- (void)sendPortMessage
{
    [self performSelectorOnMainThread:@selector(runInMainThread:) withObject:@"往往" waitUntilDone:YES];
}

- (void)runInMainThread:(NSString *)name
{
    NSLog(@"runInMainThread thread is %@.", [NSThread currentThread]);
    NSLog(@"runInMainThread name is %@.", name);
    
//    [self performSelector:@selector(runInThread:) onThread:self.thread withObject:@"牛牛汪汪" waitUntilDone:NO];
    
    [self performSelector:@selector(runInThread:) onThread:self.thread withObject:@"牛牛汪汪" waitUntilDone:NO modes:@[NSRunLoopCommonModes]];
}

- (void)runInThread:(NSString *)name
{
    NSLog(@"runInThread thread is %@.", [NSThread currentThread]);
    NSLog(@"runInThread name is %@.", name);
}

@end

打印为:

MyDream[11613:411566] viewDidLoad thread is <NSThread: 0x600000864580>{number = 1, name = main}.
MyDream[11613:411624] launchThreadWithPort thread is <NSThread: 0x6000008123c0>{number = 7, name = MyWorkerClass}.
MyDream[11613:411566] runInMainThread thread is <NSThread: 0x600000864580>{number = 1, name = main}.
MyDream[11613:411566] runInMainThread name is 往往.
MyDream[11613:411624] runInThread thread is <NSThread: 0x6000008123c0>{number = 7, name = MyWorkerClass}.
MyDream[11613:411624] runInThread name is 牛牛汪汪.

实现子线程和主线程互相通信,前提是子线程需要保活。

参考:

NSPort知识
iOS线程通信和进程通信的例子(NSMachPort和NSTask,NSPipe)

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 156,757评论 4 359
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,478评论 1 289
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 106,540评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,593评论 0 203
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 51,903评论 3 285
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,329评论 1 210
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,659评论 2 309
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,383评论 0 195
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,055评论 1 238
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,337评论 2 241
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,864评论 1 256
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,227评论 2 251
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,820评论 3 231
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 25,999评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,750评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,365评论 2 269
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,260评论 2 258

推荐阅读更多精彩内容