1

I'm trying to determine the user language in iOS. StackOverflow has several answers on this topic which has greatly helped me out, such as this one: Getting current device language in iOS?

I can successfully retrieve the value I'm looking for in NSLog (i.e. "en" or "de") but every time I question this with an if/then statement it doesn't appear to work. I have this in my viewDidLoad for testing:

- (void)viewDidLoad
{
[super viewDidLoad];
NSString *myLanguage = [[NSLocale preferredLanguages] objectAtIndex:0];
NSLog(@"The current languague is %@.", myLanguage);

if (myLanguage == @"de") {
    self.myLabel.text = @"German";
} else if (myLanguage == @"en") {
    self.myLabel.text = @"English";
} else {
    self.myLabel.text = @"didn't work";
}
}

No matter if the device is set to English or German only the last else statement is displayed. NSLog however correctly displays either en or de.

What am I doing wrong?

Community
  • 1
  • 1
Jay Versluis
  • 2,062
  • 1
  • 19
  • 18

1 Answers1

1

NSString comparison is done with isEqualToString: method. In your code you are comparing two different NSString objects, while instead you have to compare the contents of each one of them.

If you have two objects of any kind, they are always different, even if all their members have the same values. That's why methods like this exist, to compare objects based on their members.

Replace:

if (myLanguage == @"de") 

with

if ([myLanguage isEqualToString:@"de"])

and the same for the else ifs in your code.

iska
  • 2,208
  • 1
  • 18
  • 37