老谭笔记

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

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
- (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 connection
NSConnection *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)的实现部分:

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