NSString cString is Deprecated. What is the alternative?

前端 未结 1 1308
谎友^
谎友^ 2021-02-20 12:17

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

1条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-20 13:05

    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];
    

    0 讨论(0)
提交回复
热议问题