如果是其他代码检查,这是写这个的最好方法吗?
// 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";
}
感谢您的帮助
答案 0 :(得分:13)
将语言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
以避免最终的冗余,以及分散在你代码中的不可维护的文字。
答案 1 :(得分:2)
您可以使用词典(key="Country", value="code")
进行有效的操作。