我在做同样的事情时遇到了同样的问题:我有一个静态库和一个包含图像、本地化字符串等的配套捆绑文件。
我发现静态似乎无法找出正确的设备本地化(很抱歉,我无法找到此问题的原因),我已通过以下方式修复:
@implementation NSBundle (KiosKitAdditions)
+ (NSBundle *)kioskitBundle
{
static NSBundle* kioskitBundle = nil;
static dispatch_once_t predicate;
dispatch_once(&predicate, ^{
NSString *libraryBundlePath = [[NSBundle mainBundle] pathForResource:KKBundleName
ofType:@"bundle"];
NSBundle *libraryBundle = [[NSBundle bundleWithPath:libraryBundlePath] retain];
NSString *langID = [[NSLocale preferredLanguages] objectAtIndex:0];
NSString *path = [libraryBundle pathForResource:langID ofType:@"lproj"];
kioskitBundle = [[NSBundle bundleWithPath:path] retain];
});
return kioskitBundle;
}
@end
如您所见,我创建了一个 NSBundle 类别,其 Class 方法的行为与[NSBundle mainBundle] 非常相似,并为我返回了静态库的正确捆绑包,因此我可以在任何我想要的地方使用它,例如:
#define KKLocalizedString(key) NSLocalizedStringFromTableInBundle(key, @"Localizable", [NSBundle kioskitBundle], @"")
代码很简单,首先我找到静态库包的路径,找到当前的设备语言,然后创建一个新的NSBundle,其路径为 library_path/device_language.lproj 。
这种方法的一个缺点是您需要始终本地化所有资产,如果您的捆绑包中有很多图像,这可能会很痛苦(但我认为这不太可能)。
如果您不想采用我的分类方法,您可以像这样更改您的代码:
NSString *MyLocalizedString(NSString* key, NSString* comment)
{
static NSBundle* bundle = nil;
if (!bundle)
{
NSString *libraryBundlePath = [[NSBundle mainBundle] pathForResource:@"MyStaticLib"
ofType:@"bundle"];
NSBundle *libraryBundle = [NSBundle bundleWithPath:libraryBundlePath];
NSString *langID = [[NSLocale preferredLanguages] objectAtIndex:0];
NSString *path = [libraryBundle pathForResource:langID ofType:@"lproj"];
bundle = [[NSBundle bundleWithPath:path] retain];
}
return [bundle localizedStringForKey:key value:@"" table:nil];
}