I have an NSString with a value of Jose (an accent on the e). I try to convert it to a C string as follows:
char str [[myAccentStr length] + 1];
[myAccentStr getCString:str maxLength:[myAccentStr length] + 1 encoding:NSUTF32StringEncoding];
but str ends up being an empty string. What gives? I tried UTF8 and UTF16 too. It gets passed to another function later on and when that funcsion calls lstrlen on it, the size comes out as zero.
The docs for NSString getCString:maxLength:encoding says:
Using the NSString method dataUsingEncoding:allowLossyConversion: does the trick. Here’s a code example:
The output from that NSLog is:
So far I’ve only seen this work properly when using the NSMacOSRomanStringEncoding.
Edit
Changing this to a community wiki. Please feel free to edit.
hooleyhoop had some great points, so I thought I would try to make code that is as verbose as possible. If I’m missing anything, someone please chime in.
Also – Not sure why [NSString canBeConvertedToEncoding:] is returning YES even though the [NSString getCString:maxLength:encoding:] function definitely isn’t working right (as seen by the output).
Here’s some code to help in analyzing what works / what doesn’t:
Results: