我怎么能写这个,如果其他代码检查更好的方式?
这是如果其他代码检查写这个最好的方法?
// set the default to Italy if countrySaved is null if (lang == NULL) { lang = @"it"; } // otherwise set the correct lang based on the country chosed and saved in nsuserdefaults if ([countrySaved isEqual:@"Brazil"]) { lang = @"br"; } else if ([countrySaved isEqual:@"Spain"]) { lang = @"es"; } else if ([countrySaved isEqual:@"Italy"]) { lang = @"it"; } else if ([countrySaved isEqual:@"United States"]) { lang = @"us"; } else if ([countrySaved isEqual:@"United Kingdom"]) { lang = @"uk"; }
谢谢你的帮助
将语言ID存储在字典中:
NSDictionary *languageIDs = @{ @"Brazil" : @"br", @"Spain" : @"es", @"Italy" : @"it", @"United States" : @"us", @"United Kingdom" : @"uk" };
然后简单地从字典中指定lang
:
lang = languageIDs[countrySaved]; if (!lang) { lang = languageIDs[@"Italy"]; }
或者使用三元运算符来做这个更简单的方法:
lang = languageIDs[countrySaved] ?: languageIDs[@"Italy"];
另外你也许应该从plist文件中加载它们,或者使用NSString consts
常量来避免最终的冗余,并且把不可维护的文字分散到你的代码中。
您可以使用Dictionary (key="Country", value="code")
来进行高效的操作。