Re: Safe way to convert C String to NSString
Re: Safe way to convert C String to NSString
- Subject: Re: Safe way to convert C String to NSString
- From: Jens Alfke <email@hidden>
- Date: Thu, 18 Aug 2011 13:34:26 -0700
On Aug 18, 2011, at 1:22 PM, Wilker wrote:
> I did some hacks on it, using the [NSString stringWithFormat:"%s", theString] and it worked as I needed :)
Yikes — you should never, ever use ‘%s’ with NSStrings, unless you’re certain that the C string is 100% ASCII. The reason is that the conversion is done using the highly-deprecated -initWithCString:, which means it will use the “default encoding”, which (a) varies based on what locale/system language the user is using, and (b) is generally not what you want, e.g. in English it happens to be MacRoman, a highly antique encoding used by the old Classic Mac OS. So you get behavior that’s often wrong but the wrongness varies depending on what language the user speaks. Hello, tech-support nightmare.
stringWithFormat: is also a lot slower than simpler conversions.
You’re really much better off using -initWithCString:encoding:; or -initWithBytes:length:encoding: if the input data’s not NUL-terminated.
—Jens
Attachment:
smime.p7s
Description: S/MIME cryptographic signature
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden