I have an NSstring that is encoded with UTF8. I want to decode it.
I tried this but it doesn’t work:
NSString *decodedString = [NSString stringWithUTF8String:[encodedString cStringUsingEncoding:[NSString defaultCStringEncoding]]];
How can I do that?
Thanks
Sending
cStringUsingEncoding:toencodedStringcan only work ifencodedStringis an NSString object. Having an NSString object is the point you’re trying to get to. Moreover, that method does not decode the string, it encodes the string using the encoding you ask for; thus, in the code you show, you ask for the (already-encoded) string to be encoded in some random encoding (the default C string encoding), then attempt to decode the result as UTF-8. That won’t work.You don’t specify what type you’re using for
encodedString. Either way, you need to create the NSString object by passingencodedStringand its encoding.encodedStringis an NSData object, use theinitWithData:encoding:method.initWithCString:encoding:method or (only when it’s UTF-8) theinitWithUTF8String:method.initWithBytes:length:encoding:method.All of these except
initWithUTF8String:require you to specify the encoding (initWithUTF8String:does by definition), and all of them exceptinitWithData:encoding:come in an autoreleasing convenience version (+stringWith…instead of-initWith…).