我发现一个更简单的方法来使用NSConnection对象来做到这一点。我创建了这个头一个非常简单的ExitListener对象:
@interface ExitListener : NSObject {
BOOL _exitRequested;
NSConnection *_connection;
}
@property (nonatomic, assign) BOOL exitRequested;
- (void)requestExit;
@end
实施这一项目:
@implementation ExitListener
@synthesize exitRequested = _exitRequested;
// On init we set ourselves up to listen for an exit
- (id)init {
if ((self = [super init]) != nil) {
_connection = [[NSConnection alloc] init];
[_connection setRootObject:self];
[_connection registerName:@"com.blahblah.exitport"];
}
return self;
}
- (void)dealloc {
[_connection release];
[super dealloc];
}
- (void)requestExit {
[self setExitRequested:YES];
}
@end
要设置监听器,后台进程只是简单的分配和inits的ExitListener的一个实例。桌面应用程序然后要求后台过程在进行此调用退出:
- (void)stopBackgroundProcess {
// Get a connection to the background process and ask it to exit
NSConnection *connection = [NSConnection connectionWithRegisteredName:@"com.blahblah.exitport" host:nil];
NSProxy *proxy = [connection rootProxy];
if ([proxy respondsToSelector:@selector(requestExit)]) {
[proxy performSelector:@selector(requestExit)];
}
}
使用NSMachPorts直接似乎导致注册和获得引用远远更多的问题。我发现NSConnection是为需要解决的情况创建基本通信渠道的最简单方式。
hooray让程序让用户关闭(有时)不需要的后台进程! – 2010-04-27 19:17:30
在发布查询之前,我想出了我的NSMachPort的实现问题。事实证明,NSMachBootstrapServer不喜欢注册使用特定端口号初始化的端口。当我使用默认的初始化调用时,一切正常。 – mcsheffrey 2010-04-27 19:23:27