Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSString cString is Deprecated. What is the alternative?

I've got another newbie question.

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

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];
like image 970
manospro Avatar asked Dec 29 '10 07:12

manospro


1 Answers

  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];
like image 125
Jacob Relkin Avatar answered Oct 16 '22 11:10

Jacob Relkin