我有另一个新手问题.
我写了一段代码,将NSString转换为NSMutableData,以模拟一个webService结果.
但事实证明,cString已被弃用.你可以帮我更换吗?
这是我的代码
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];
解决方法
>从字符串获取原始字节.
>获取UTF8编码中这些字节的长度.
>使用dataWithBytes:length:方法创建NSData对象.
>获取UTF8编码中这些字节的长度.
>使用dataWithBytes:length:方法创建NSData对象.
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];