Objective c 如何定位动态对象?
我的应用程序从一台JSON服务器中提取一些以两种语言本地化的动态内容,如下所示:Objective c 如何定位动态对象?,objective-c,oop,localization,Objective C,Oop,Localization,我的应用程序从一台JSON服务器中提取一些以两种语言本地化的动态内容,如下所示: Banners: [ { BannerId: 1, Headline: { en: "English String", fr: "French String" } }] 我想创建一个名为Banner的对象,它有一个属性标题,其getter返回字符串的本地化版本,就像NSLocalizedString为静态内容选择正确的字符串一样 是否可以使用NSLocali
Banners: [
{
BannerId: 1,
Headline: {
en: "English String",
fr: "French String"
}
}]
我想创建一个名为Banner的对象,它有一个属性标题,其getter返回字符串的本地化版本,就像NSLocalizedString为静态内容选择正确的字符串一样
是否可以使用NSLocalizedString进行此操作,或者是否有其他方法?据我所知,
NSLocalizedString()
及其所有变体都在您的应用程序包中工作。理论上,如果可以将对象的内容序列化到应用程序包中的.strings
文件中,您可以使用它们(更准确地说,是NSLocalizedStringFromTable()
。。不幸的是,应用程序包不可写,因此我非常确信您不能使用这些函数宏
您可以做的是获取当前系统语言标识符,然后将其用作反序列化词典的索引:
NSString *curSysLang = [NSLocale preferredLanguages][0];
NSString *headline = jsonObject[0][@"Headline"][curSysLang];
我最终创建了一个名为NSLocalizedObject的类,该类有一个dictionary属性,用于存储两种语言的数据。然后我创建了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];
}
请注意,您可以检查操作系统设置的实际语言,但我有一个要求,即用户可以更改应用程序的语言,而不管操作系统的当前语言如何