Difference between – displayNameForKey:value: and - objectForKey: in NSLocale Class

StackOverflow https://stackoverflow.com/questions/10869358

  •  12-06-2021
  •  | 
  •  

Question

Hi just a quick question what is the difference between – displayNameForKey:value: and - objectForKey: in NSLocale Class? I searched online but didn't get it. Thank you.

Apple Document

displayNameForKey:value:
Returns the display name for the given value.

- (NSString *)displayNameForKey:(id)key value:(id)value
Parameters
key
Specifies which of the locale property keys value is (see “Constants”),
value
A value for key.
Return Value
The display name for value.



objectForKey:
Returns the object corresponding to the specified key.

- (id)objectForKey:(id)key
Parameters
key
The key for which to return the corresponding value. For valid values of key, see “Constants.”
Return Value
The object corresponding to key.
Était-ce utile?

La solution

You use displayNameForKey:value: to get a label suitable for display based on the locale object you are calling. For instance:

NSLocale *french = [[[NSLocale alloc] initWithLocaleIdentifier:@"fr_FR"] autorelease];
NSString *frenchName = [french displayNameForKey:NSLocaleIdentifier value:@"fr_FR"];

NSLocale *english = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease];
NSString *englishName = [english  displayNameForKey:NSLocaleIdentifier value:@"fr_FR"];

NSLog(@"French locale in French is called '%@'", frenchName);
NSLog(@"French locale in English is called '%@'", englishName);

will produce the output:

French locale in French is called 'français (France)'
French locale in English is called 'French (France)'

There are plenty of examples in the NSLocale Class Reference.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top