不建议使用NSString cString。有什么选择? [英] NSString cString is Deprecated. What is the alternative?

查看:132
本文介绍了不建议使用NSString cString。有什么选择?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我还有另一个新手问题。

I've got another newbie question.

我写了一段代码,将NSString转换为NSMutableData,以模拟webService结果。

I've written a piece of code that converts a NSString to NSMutableData in order to simulate a webService result.

事实证明,不建议使用cString。你能帮我更换吗?
这是我的代码。

It turns out however that cString is deprecated. Can you help me replace it? Here's my code.

NSString *testXMLDataString = 
@"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
    etc....
"</SOAP-ENV:Envelope>";

//Replace webData Received from the web service with the test Data
NSMutableData *testXMLData = [NSMutableData dataWithBytes:[testXMLDataString cString] length:[testXMLDataString length]];
[webData setData:testXMLData];


推荐答案


  1. 获取原始字节

  2. 以UTF8编码获取这些字节的长度。

  3. 创建 NSData 对象,使用 + dataWithBytes:length:方法。

  1. Get the raw bytes from the string.
  2. Get the length of those bytes in the UTF8 encoding.
  3. Create the NSData object using the +dataWithBytes:length: method.







const char *rawBytes = [testXMLDataString UTF8String];
const NSUInteger length = [testXMLDataString lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
NSAssert(length > 0, @"Couldn't convert to UTF-8");

NSMutableData *testXMLData = [NSMutableData dataWithBytes:rawBytes length:length];
[webData setData:testXMLData];

这篇关于不建议使用NSString cString。有什么选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆