Question

For example, why use this:

NSLocale *l = [[NSLocale alloc] initWithLocaleIdentifier@"en_US"];

Instead of something like this:

NSLocale *l = [[NSLocale alloc] initWithLocaleIdentifier:NSLocaleIdentifierUS];

It seems like it would prevent a lot of errors, as when typing an NSString in Xcode, there is no autocorrect, while Xcode will autocorrect/autofill enums. Additionally, I can't think of a reason to use NSStrings over enums or constants. For example, as new versions of the SDK are released, Apple can add new identifiers, but they can also do this with enums. Another benefit of enums over string constants is that enums can be compared more easily:

if(userIdentifier == NSLocaleIdentifierUS) {

    //English!
}

Also, for other methods, Apple uses enums or specific objects as parameters:

NSData *data = [aString dataUsingEncoding:NSASCIIStringEncoding];

If they use a string for localeIdentifier, why not do this:

NSData *data = [aString dataUsingEncoding:@"ascii"];

It seems like they are simply being inconsistent.

Était-ce utile?

La solution

There are several answers to this question suggested by the comments:

  1. There are hundreds of locales, and many variations of the ones that already exist (ex. there is "en_US" and "en_US_POSIX", so it would be impractical to create this many enums.
  2. When reading data from a web service, the format used is "lang_COUNTRY", so it would make sense to have the same format to avoid having parse web data every time one downloaded locale data from the web.
  3. Strings are objects, so they can easily be stored in collections without wrapping them in an NSNumber object, as would be the case with enums.
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top