It turns out that the wchar
array that was passed in sometimes had UTF-16 characters in it, and UTF-16 encodes multibyte characters differently. And if initWithBytes
gets invalid data, it returns nil
.
NSString initWithBytes returns nil when given wchar_t array containing Chinese characters
-
24-06-2022 - |
Question
I've got a custom C++ string class in my iOS app that is based on an array of wchar_t
. I have a method to convert it to NSString
that looks like this:
NSString *str = [[[NSString alloc]initWithBytes:(const void *)mArray
length:sizeof(wchar_t) * mLength
encoding:NSUTF32LittleEndianStringEncoding]autorelease];
return str;
I've got a case where the input string contains some Chinese characters (specifically 新譯本), and initWithBytes
returns nil. There is nothing in the documentation about the method returning nil; is this an error condition? Does anyone know what kind of thing might make the method kick back a nil result?
Solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow