Objective c 使用带有ARC的C API时,EXC_访问错误

Objective c 使用带有ARC的C API时,EXC_访问错误,objective-c,ios,automatic-ref-counting,Objective C,Ios,Automatic Ref Counting,当使用Bonjour(使用中的函数)连接到主机时,我使用以下代码查找服务器主机名 和我的iOS Objective-C代码中的)。我使用的代码(如下所示)来自Big Nerd Ranch iOS编程书,但最初并没有考虑到ARC - (NSString *)serverHostName { NSArray *addresses = [desktopServer addresses]; NSData *firstAddress = [addresses objectAtIndex:0

当使用Bonjour(使用
中的函数)连接到主机时,我使用以下代码查找服务器主机名 和我的iOS Objective-C代码中的
)。我使用的代码(如下所示)来自Big Nerd Ranch iOS编程书,但最初并没有考虑到ARC

- (NSString *)serverHostName
{
    NSArray *addresses = [desktopServer addresses];
    NSData *firstAddress = [addresses objectAtIndex:0];

    // the binary data in the NSData object is a sockaddr_in (which represents a network host)
    const struct sockaddr_in *addy = [firstAddress bytes];

    // convert 4-byte IP address in network byte order to a C string of the format xxx.xxx.xxx.xxx
    char *ipAddress = inet_ntoa(addy->sin_addr);

    // convert the 2-byte port number from network to host byte order
    UInt16 port = ntohs(addy->sin_port);

    return [NSString stringWithFormat:@"%s:%u", ipAddress, port];
}
它偶尔会在
char*ipAddress=inet\u ntoa(addy->sin\u addr)行上出现EXC\u BAD\u访问时崩溃
,让我相信,
addy
被处理得太快了。我尝试过使用
cfbrigingRetain()
CFRetain()
方法来防止这种情况发生,但它们要么没有效果,要么似乎会带来更多问题


关于我应该寻找什么来消除这种情况,有什么建议吗?

你确定在这种情况下NSData不是
nil
吗?哎呀,我觉得很傻。似乎就是这样。始终检查
nil
:)。这是当某件事情开始像这样运行时我要做的第一件事。在第二行中,如果
地址
也为零,那么唯一可以毫无例外地发生的方法就是。因此,尽管检查nil并不是坏事,但您可能希望进一步返回,看看
desktopServer
在创建
地址时所做的任何操作是否有问题。