NSXPCConnection调试中断/失效

Pat*_*ita 5 nsxpcconnection xcode9

我使用的是 XCode 9、OSX,而​​不是 iOS、Objective-C。

我有一个 XPC 服务可以与其他应用程序通信。XPC 服务对我来说是全新的。我已经阅读了我找到的文档和文章 - 但我仍然需要一些帮助。

// NSXPC Connection stored as ivar
self.bridgeagent = [[NSXPCConnection alloc] initWithServiceName:@"com.myid.myapp.bridgeagent"];
self.bridgeagent.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(bridgeagentProtocol)];
self.bridgeagent.exportedInterface = [NSXPCInterface interfaceWithProtocol:@protocol(bridgeagentProxyProtocol)];
self.bridgeagent.exportedObject = self;

[self.bridgeagent setInvalidationHandler:^{
    NSLog(@"Bridgeagent invalidation handler!");
}];

[self.bridgeagent setInterruptionHandler:^{
    NSLog(@"Bridgeagent interruption handler!");
}];

[self.bridgeagent resume];
Run Code Online (Sandbox Code Playgroud)

该服务的调用方式如下:

// openFile method is listed in corresponding protocol
[[self.bridgeagent remoteObjectProxyWithErrorHandler:^(NSError * _Nonnull error) {
NSLog(@"bridgeagent.openFile errorHandler: %@",error);
}] openFile:parameters withReply:^(NSDictionary *returnParameters) { // do something with result }];
Run Code Online (Sandbox Code Playgroud)

呼叫成功,服务完成其工作。然而,既然该服务可以正常工作,我想深入研究使其更加稳定(即使我现在没有遇到任何问题)。

有人可以向我解释一下吗

  1. 中断和失效之间的区别(当其中之一发生时不要理解)
  2. 是否有处理这两种情况的最佳实践
  3. 如何强制这两种情况(用于调试)

谢谢你的帮助

小智 5

回答问题1:

[self.xpcConnection setInterruptionHandler:^{
    // Connection interrupted. Backend (service) may have crashed.
    // connection used to work but suddenly terminated
}];

[self.xpcConnection setInvalidationHandler:^{
    // No one is listening. Is the backend running?
    // connection cannot be established
}];
Run Code Online (Sandbox Code Playgroud)

回答问题3:

中断:使后端在事务中间退出(就在发送回复之前)

失效:根本不启动后端(服务)

回答问题2:

我听说,如果发生“中断”,您应该尝试重新建立连接。当您的服务是一个启动代理时,如果它崩溃了,它会被 launchd 重新启动,这会很有用。

实际上,在我的程序中,我不会对这些情况采取行动,而只是向命令行发出警告消息。我的前端是一个 cli 程序。或者,您可以将此警告记录在日志文件中,例如使用 syslog。请参阅“man 3 syslog”。在我的应用程序中,我使用自己的日志文件,其详细程度和系统日志可配置。

亲切的问候,

罗伯特