5

在我的“ViewController.swift”中,我有一个本地化字符串:

TheOutLabel.text = NSLocalizedString("hello", comment: "The \"hello\" word")

在终端中,为了生成“Localizable.strings”文件,我输入:

cd Base.lproj/; genstrings ../*.swift; cat Localizable.strings

并得到以下结果:

??/* The \"hello\" word */
"hello" = "hello";

输入时od -c Localizable.strings,我得到:

0000000  377 376   /  \0   *  \0      \0   T  \0   h  \0   e  \0      \0
0000020    \  \0   "  \0   h  \0   e  \0   l  \0   l  \0   o  \0   \  \0
0000040    "  \0      \0   w  \0   o  \0   r  \0   d  \0      \0   *  \0
0000060    /  \0  \n  \0   "  \0   h  \0   e  \0   l  \0   l  \0   o  \0
0000100    "  \0      \0   =  \0      \0   "  \0   h  \0   e  \0   l  \0
0000120    l  \0   o  \0   "  \0   ;  \0  \n  \0  \n  \0                

当我输入file Localizable.strings时,它说:

Localizable.strings: Little-endian UTF-16 Unicode c program text

当我用“emacs”打开文件时,它不显示这些字符,当我输入时M-x describe-current-coding-system RET,它说:

Coding system for saving this buffer:
  U -- utf-16le-with-signature-unix (alias: utf-16-le-unix)

所以,文件开头的这些八进制字符 \377 和 \376 看起来有点像 utf-16-le BOM,这就解释了为什么每个字符后跟一个 \0(UTF-16 比在这种情况下为 UTF-8)。

这是正常的/有用的/有害的吗?

此外,标准 *nix 工具 ( grep, sed, awk) 不能很好地处理 utf-16 文件:

grep '=' Localizable.strings 
Binary file Localizable.strings matches

grep -a '=' Localizable.strings | sed -e 's/ = //'
"hello" = "hello";

另外,我编辑了 Localizable.strings 以替换"hello";"Hello";. 然后“SourceTree”(我的“git”客户端)无法显示差异,除非我这样做,正如我可以让 git 将 UTF-16 文件识别为文本吗?

echo '*.strings diff=localizablestrings' > .../.git/../.gitattributes
echo '[diff "localizablestrings"]' >> .../.git/config
echo '  textconv = "iconv -f utf-16 -t utf-8"' >> .../.git/config

Apple 的国际化和本地化指南说:

注意:如果 Xcode 警告您 Localizable.strings 文件似乎是 Unicode (UtF-16),您可以使用文件检查器将其转换为 Unicode (UTF-8)。

那么,我应该删除/忽略 BOM 吗?

似乎没有genstrings生成 UTF-8 文件的选项。

我应该转换文件吗?

4

1 回答 1

0

genstrings工具经过硬编码以输出编码为“UTF-16LE with BOM”的字符串文件。我更喜欢将我的字符串文件保存在 UTF-8 中,并使用以下 shell 脚本来生成它们:

#!/bin/zsh
function convert {
    for file in $@; do
        print "Converting $file to UTF-8"
        iconv -f utf-16 -t utf-8 $file > temp   
        rm $file; mv temp $file
    done
}
genstrings -o en.lproj *.m
convert en.lproj/*.strings
于 2021-09-14T08:24:30.603 回答