objective-c - 检测/修复 NSConnection 故障

标签 objective-c cocoa nsconnection

我想使用 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/

相关文章:

cocoa - 在 Mac OS X 上进行进程间通信的最佳方式

ios - 如何在 XCode 中使用 NSConnection 进行 JSON 延迟加载?

iphone - Objective-C "miscasting"使用 stringWithFormat 和 %d 的字符串/int

objective-c - 在 objective-c cocoa 应用程序中获取屏幕上像素的颜色

iphone - 核心数据: does a fetch have to make a trip to persistent store?

cocoa - 如何检测任务控制或 Command-Tab 切换器取代了 OS X 中的程序?

objective-c - 在 Cocoa 应用程序中使用 XML-RPC 的最佳方式?

ios - iOS 上处理互联网访问网站认证

ios - tabbarcontroller下tableview最后一行被截断

objective-c - Objective-C : Adaptive Toolbar On Orientation Change