我想使用 NSConnection/NSDistributedObject 进行进程间通信。我希望客户端能够处理服务器仅偶尔可访问的情况。
如何确定向 NSConnection 发送消息是否会失败或已经失败?目前,如果我的服务器(出售远程对象的进程)死机,客户端向远程对象发送选择器时将崩溃。
理想情况下,我希望有一个远程对象的包装器,它可以延迟实例化(或重新实例化)连接,并在无法实例化连接或连接失败的情况下返回默认值。我真的不知道使用 Objective c 执行此操作的正确方法。
这是一些代表此逻辑的伪代码:
if myConnection is null:
instantiate myConnection
if MyConnection is null:
return defaultValue
try
return [myConnection someMethod]
catch
myConnection = null
return defaultValue
最佳答案
不幸的是,检测连接失败的唯一方法是使用异常处理程序,因为没有可靠的方法来“询问”远程对象连接是否仍然有效。值得庆幸的是,这很简单:
//get the distributed object
id <YourDOProtocol> remoteObject = (id <YourDOProtocol>)[NSConnection rootProxyForConnectionWithRegisteredName:@"YourRegisteredName" host:yourHost];
//call a method on the distributed object
@try
{
NSString* response = [remoteObject responseMethod];
//do something with response
}
@catch(NSException* e)
{
//the receiver is invalid, which occurs if the connection cannot be made
//handle error here
}
关于objective-c - 检测/修复 NSConnection 故障,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2649059/