用NSConnection实现不同进程间的通信

来源:互联网 发布:日本尼达利淘宝店 编辑:程序博客网 时间:2024/06/05 13:32

用NSConnection实现不同进程间的通信

在Mac应用程序开发中可能会这样做:让程序的某部分逻辑放置在一个独立的进程之中,如文件或程序的监控、Crash报告的回传等等,但不同的进程之间的通信就再所难免,今天尝试了通过NSConnection实现不同进程间的通信,实在是非常方便小巧,使用起来也很灵活,好的,帖代码。

程序1(线程1)中建立一个类:

12345678910111213141516171819202122232425262728293031
- (id)init{    self = [super init];    if (self) {        // renderThread线程维护NSConnection的通信.        renderThread = [[NSThread alloc] initWithTarget:self                                               selector:@selector(threadMain)                                                 object:nil];    }    return self;}- (void)threadMain{NSAutoreleasePool * pool = [NSAutoreleasePool new];NSRunLoop* myRunLoop = [NSRunLoop currentRunLoop];//setup server connectionNSConnection *serverConnection = [NSConnection new];        //设置self为NSConnection的代理对象        [serverConnection setRootObject:self];        //connectionName是注册名称        [serverConnection registerName:@"connectionName"];[myRunLoop run];[pool release];}- (void)test{    //do something    NSLog("test");}

这样,线程1的代码就已经完成了。
下面是程序2(线程2)的实现部分:

1234
//这样就可以通过name取得注册的NSConnection的代理对象NSDistantObject *drawer = [NSConnection rootProxyForConnectionWithRegisteredName:@"connectionName" host:nil];//调用代理对象中的方法,就跟普通对象一样,当然如果为了让代理对象的方法可见,可以定义公共的协议protocol[drawer performSelector:@selector(test)];
0 0
原创粉丝点击