使用ARC将NSString *转换为char *

时间:2012-11-14 15:58:54

标签: objective-c xcode network-programming

我正在尝试在Iphone应用程序中执行以下设置udp连接,如下所示:

 struct sockaddr_in server_address;
 CFDataRef server_address_data;
  ....      


  memset(&server_address, 0, sizeof(server_address));
  server_address.sin_len = sizeof(server_address);
  server_address.sin_family = AF_INET;
  server_address.sin_port = htons(thePort);      
  inet_aton([theHost cStringUsingEncoding:[NSString UTF8String]], &server_address.sin_addr);
  // put server address into CFData
  server_address_data = CFDataCreate(NULL, (uint8_t *) &server_address, sizeof(server_address));
  // set timeout (ACK and RESULT packets) for socket
  ????

现在,我遇到了以下问题:变量theHost来自TextField,类型为NSString *。我想从它获取IP地址,因此尝试inet_aton,它需要一个char *。如何对其进行转换(使用ARC)?我上面的尝试失败了,因为“没有选择器UTF8String的已知类方法”。 另外,我想在接收时为我的套接字设置超时..

3 个答案:

答案 0 :(得分:2)

-UTF8String是一种实例方法,因此您需要使用[theHost UTF8String],它将返回char *

答案 1 :(得分:2)

只需使用[NSString UTF8String]获取UTF-8编码的字符串:

inet_aton([theHost UTF8String], &server_address.sin_addr);

答案 2 :(得分:0)

您编写了[NSString UTF8String],但UTF8String不是静态方法,因此您首先要创建该字符串的实例,您可以用以下代码替换该行:

inet_aton([theHost cStringUsingEncoding:[@"String that you want" UTF8String]], &server_address.sin_addr);