如何本地化动态对象?

时间:2013-08-11 17:35:46

标签: objective-c oop localization

我的应用程序从JSON中的服务器中提取一些以两种语言本地化的动态内容,如下所示:

Banners: [
{
    BannerId: 1,
    Headline: {
        en: "English String",
        fr: "French String"
    }
}]

我想创建一个名为Banner的对象,该对象具有Headline属性,其getter返回字符串的本地化版本,与NSLocalizedString为静态内容选择正确的字符串的方式相同。

是否可以为此使用NSLocalizedString或有其他方法吗?

2 个答案:

答案 0 :(得分:0)

据我所知,NSLocalizedString()及其所有变体都适用于您的应用包。理论上,如果可以将对象的内容序列化为应用程序包中的NSLocalizedStringFromTable()文件,则可以使用它们(更确切地说,.strings很遗憾,app bundle不可写,所以我非常有信心你不能使用这些函数宏。

您可以做的是获取当前的系统语言标识符,然后将其用作反序列化字典的索引:

NSString *curSysLang = [NSLocale preferredLanguages][0];
NSString *headline = jsonObject[0][@"Headline"][curSysLang];

答案 1 :(得分:0)

我最终创建了一个名为NSLocalizedObject的类,它有一个存储两种语言数据的字典属性。然后我创建了getter和setter,它检查了应用程序所在的当前语言,并以适当的语言返回数据。我需要本地化的所有数据模型类都继承自此类。

-(NSObject *)getLocalizedObjectForProperty:(NSString *)property {
    NSDictionary *objs = [_propertyDictionary objectForKey:property];
    NSString *lang = [[NSUserDefaults standardUserDefaults] objectForKey:@"currentLanguage"];


    return [objs objectForKey:lang];


}

-(NSObject *)getLocalizedObjectForProperty:(NSString *)property forLanguage:(NSString *)lang {
    NSDictionary *objs = [_propertyDictionary objectForKey:property];

    return [objs objectForKey:lang];


}
//takes a whole localized json style object - like {@"en":bleh, @"fr:bleh}
-(void)setLocalizedObject:(NSDictionary *)obj forProperty:(NSString *) property {
    [_propertyDictionary setObject:obj forKey:property];
}

//allows you to set an object for a specific language
-(void)setObject:(NSObject *)obj forProperty:(NSString *) property forLang:(NSString *)lang {

    //if a language isn't handed in then it means it should be set for the current language
    //applicable in the case where I want to save an image that is downloaded to the current language for that image.
    if (!lang) lang = DEFAULTS(@"currentLanguage");

    //get a mutable version of the dictionary for the property you want to set
    NSMutableDictionary *mutObjs = (NSMutableDictionary *)[_propertyDictionary objectForKey:property];

    //if the above call returns nil because the dictionary doesn't have that property yet then initialize the dictionary
    if (!mutObjs) {
        mutObjs = [NSMutableDictionary dictionary];
    }

    //set the obj for the correct language
    [mutObjs setObject:obj forKey:lang];

    //store the property back into the propertyDictionary
    [_propertyDictionary setObject:(NSDictionary *)mutObjs forKey:property];

}

请注意,您可以检查操作系统设置的实际语言,但我要求用户可以更改应用程序的语言,尽管操作系统的当前语言。