Читать файл.strings в Objective-C?

Я создаю приложение для Mac и хочу локализовать свои ярлыки. Я думал .strings файл будет лучшим выбором. Но у меня проблемы с чтением .strings файл в Objective-C. Я ищу более простой метод.

Это мое .string содержание файла:

"LABEL_001" = "Start MyApp";
"LABEL_002" = "Stop MyApp";
"LABEL_003" = "My AppFolder";
...

Я уже посмотрел на http://developer.apple.com/library/mac/#documentation/cocoa/conceptual/LoadingResources/Strings/Strings.html.

Это мой код:

NSBundle *bundle = [NSBundle mainBundle];
NSString *strFilePath = [[NSBundle mainBundle] pathForResource:@"Labels" ofType:@"strings"];
NSString *tt =NSLocalizedStringFromTableInBundle(@"LABEL_001",strFilePath,bundle, nil);
NSLog(@"STRING ::: %@",tt);

Но строка тт дает "LABEL_001", Я хочу "Start MyApp"

Что я делаю неправильно?

4 ответа

Решение

Один. Вы должны назвать свой файл Localizable.strings в <LANGUAGENAME>.lproj каталог в комплекте приложения.

Два. Использовать NSLocalizedString макрос:

NSString *loc = NSLocalizedString(@"LABEL_001", nil);

Три. Если ничего не работает, вы можете инициализировать NSDictionary, используя файл строк, поскольку файл строк представляет собой специальный тип plist:

NSString *fname = [[NSBundle mainBundle] pathForResource:@"whatever" ofType:@"strings"];
NSDictionary *d = [NSDictionary dictionaryWithContentsOfFile:fname];
NSString *loc = [d objectForKey:@"LABEL_001"];
    NSString *path = [[NSBundle mainBundle] pathForResource:@"Labels" ofType:@"strings"];
    NSData *plistData = [NSData dataWithContentsOfFile:path];
    NSString *error; NSPropertyListFormat format;

    NSDictionary *dictionary = [NSPropertyListSerialization propertyListFromData:plistData
                                                          mutabilityOption:NSPropertyListImmutable
                                                                    format:&format
                                                          errorDescription:&error];
    NSString *stringname = [dictionary objectForKey:@"LABEL_001"];

Я думаю, что это будет полезно для вас.

Вот твой код

NSBundle *bundle = [NSBundle mainBundle];
NSString *strFilePath = [[NSBundle mainBundle] pathForResource:@"Labels" ofType:@"strings"];
NSString *tt =NSLocalizedStringFromTableInBundle(@"LABEL_001",strFilePath,bundle, nil);
NSLog(@"STRING ::: %@",tt);

Проблема здесь заключается во втором параметре "strFilePath", замените его на @"Labels", чтобы приведенный выше код стал

NSString *tt =NSLocalizedStringFromTableInBundle(@"LABEL_001",@"Labels",bundle, nil);

Для справки, следующая строка, скопированная из Apple Docs относительно имени таблицы: "При указании значения для этого параметра включайте имя файла без расширения.strings".

надеюсь это поможет.

Простой код

Просто создайте метод следующим образом

- (void)localisationStrings
{
    NSString* path = [[NSBundle mainBundle] pathForResource:@"localisation" ofType:@"strings"];
    NSDictionary *localisationDict = [NSDictionary dictionaryWithContentsOfFile:path];
    NSLog(@"\n %@",[localisationDict objectForKey:@"hello"]);
}
Другие вопросы по тегам