Strings, Unicode, Localization, and Parsing
The new issue of objc.io is all about strings.
The truth is that an
NSString
object actually represents an array of UTF-16-encoded code units. Accordingly, thelength
method returns the number of code units (not characters) in the string. At the time whenNSString
was developed (it was first published in 1994 as part of Foundation Kit), Unicode was still a 16-bit encoding; the wider range and UTF-16’s surrogate character mechanism were introduced with Unicode 2.0 in 1996. From today’s perspective, theunichar
type and thecharacterAtIndex:
method are terribly named because they tend to promote any confusion a programmer may have between Unicode characters (code points) and UTF-16 code units.codeUnitAtIndex:
would be a vastly better method name.
We must never use
-uppercaseString
or-lowercaseString
for strings that are supposed to be displayed in the UI. Instead, we must use-uppercaseStringWithLocale:
[…]
When using the
NSLocalizedString
macro, the first argument you have to specify is a key for this particular string. You’ll often see that developers simply use the term in their base language as key. While this might be convenient in the beginning, it is actually a really bad idea and can lead to very bad localizations.[…]
Good localizable string keys have to fulfill two requirements: first, they must be unique for each context they’re used in, and second, they must stick out if we forgot to translate something.
We recommend using a name-spaced approach[…]
[…]
When using date and number formatters or methods like
-[NSString lowercaseStringWithLocale:]
, it’s important that you use the correct locale. If you want to use the user’s systemwide preferred language, you can retrieve the corresponding locale with[NSLocale currentLocale]
. However, be aware that this might be a different locale than the one your app is running in.
Scanning a hex color is the same as before. The only difference is that we have now wrapped it in a method, and use the same pattern as
NSScanner
methods. It returns aBOOL
indicating successful scanning, and stores the result in a pointer to aUIColor
[…]