IOS NSString in UTF16


I have a string that I fetched from an Apache server over HTTP:

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

I need to make that string a UTF16 string. I don't want to turn it into NSData. I need to keep it NSString and I need it to be in UTF16.
I would be happy to put it in an NSData object even, if I could do it as UTF16. I'm doing something similar now:

[self.returnedData appendData:data];

But that still transfers it as UTF8.
It's probably simple and I'm missing it. But I don't find it in the Apple docs or this site, and my Google-Fu has failed me.
What am I missing? How do I do that?
Thanks for your time and help.

Ok. All of what you and Justin have said makes sense and makes things make more sense.
So this is what I am doing. It seems to be correct from this line but I wanted to make sure I am understanding you correctly.

NSData *resultData = [self. result dataUsingEncoding:NSUTF16LittleEndianStringEncoding];
NSString *resultStr = [[NSString alloc] initWithData:resultData encoding:NSUTF16LittleEndianStringEncoding];
NSString *md5Result = [[NSString stringWithFormat:@"%@",[resultStr MD5]] uppercaseString];
NSLog(@"md5Result = %@",md5Result);

That last part is what I am doing with the string after it's UTF-16. I have a category that makes it an MD5 hex string similar to
Thanks again. I'll bump you guys both and say this is the right answer.

Best Solution

A string is a string is a string. The encoding refers to how its encoded and decoded to and from NSData. @"blah" is the same as @"blah". There is no UTF8 or UTF 16 for either of those.

Added So you can do [@"myString" dataUsingEncoding:NSUTF16StringEncoding];

If you convert that back to a string, you'll still have @"myString"

Answer last question in comment below. So when you POST to a server the server body is encoded data. So what you wanted to do is do what ever you want to the string. THEN convert the string to data using a particular encoding, in your case, NSUTF16StringEncoding or NSUTF16LittleEndianStringEncoding. You are NOT creating UTF-16 string. You are converting a unicode string to UTF-16 encoded data. This is what you need to do then.

NSData *postBody = [[[self.result MD5] uppercaseString] dataUsingEncoding:NSUTF16LittleEndianStringEncoding];

If you need to add more data to the postBody create NSMutableData instead and append the new data as needed.

Related Question