13

我有一个基本的 Swift 文件Test.swift,其中包含

import Foundation
import UIKit

class Test: NSObject {
    let a: String
    let b: String

    override init() {
        a = NSLocalizedString("key 1", tableName: nil,
            bundle: NSBundle.mainBundle(), value: "value 1", comment: "comment 1")
        b = NSLocalizedString("key 2", comment: "comment 2")
    }
}

当我genstrings在这个文件上运行时,我收到了一个意外的警告

$ genstrings -u Test.swift
Bad entry in file Test.swift (line = 9): Argument is not a literal string.

并且生成的Localizable.strings文件缺少条目"key 1"

$ cat Localizable.strings 
??/* comment 2 */
"key 2" = "key 2";

但是,当我在文件中使用以下代码在 Objective-C 中执行等效操作时Test.m

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface Test: NSObject

@property (nonatomic, strong) NSString *a;
@property (nonatomic, strong) NSString *b;

@end

@implementation Test

- (id)init {
    self = [super init];
    if (self) {
        self.a = NSLocalizedStringWithDefaultValue(@"key 1", nil, [NSBundle mainBundle], @"value 1", @"comment 1");
        self.b = NSLocalizedString(@"key 2", @"comment 2");
    }
    return self;
}

@end

genstrings命令按预期工作,我得到"key 1".

$ genstrings -u Test.m 
$ cat Localizable.strings 
??/* comment 1 */
"key 1" = "value 1";

/* comment 2 */
"key 2" = "key 2";

我究竟做错了什么?

4

2 回答 2

29

显然,Apple 已经不再支持 genstrings。而是使用:

xcrun extractLocStrings

作为你的命令。例如,为您的项目创建 Localizable.strings:

find ./ -name "*.m" -print0 | xargs -0 xcrun extractLocStrings -o en.lproj

对于斯威夫特:

find ./ -name "*.swift" -print0 | xargs -0 xcrun extractLocStrings -o en.lproj

请注意,如果您要导出到 .xliff 文件,则根本不需要像 xCode 那样运行 genstrings

编辑器 > 导出以进行本地化

命令将在“幕后”处理您的字符串。

更新:我在 xCode 7.3.1 上,在我的系统上 xtractLocStrings 是一个二进制文件。

$ file /Applications/Xcode.app//Contents/Developer/usr/bin/extractLocStrings
    /Applications/Xcode.app//Contents/Developer/usr/bin/extractLocStrings: Mach-O 64-bit executable x86_64

这是我的测试:

let _ = NSLocalizedString("1st", comment: "1st string")
let _ = NSLocalizedString("Second", tableName: "Localized", bundle: NSBundle.mainBundle(), value: "2nd", comment: "2nd string”)

结果如下:

Localizable.strings:
/* 1st string */
"1st" = "1st”;

Localized.strings:
/* 2nd string */
"Second" = "2nd”;
于 2016-07-01T11:06:52.663 回答
15

这是 Xcode 6.4 和 Xcode 7 beta 中的 genstrings 错误,如https://openradar.appspot.com/22133811中所述:

在 Swift 文件中, genstrings Chokes On NSLocalizedString 调用带有两个以上的参数

总结:当对 Swift 文件运行 genstrings 时,如果有任何 NSLocalizedString 调用使用了“value”和“comment”参数之外的普通情况,genstrings 就会出错。...

于 2015-08-14T20:16:00.307 回答