肇鑫的技术博客

业精于勤,荒于嬉

NSLocalizedString的特殊用法

一般情况下,我们使用NSLocalizedString来加工需要翻译的字符串,如:

let says = NSLocalizedString("Hello World!", comment: "hello world")

一般情况这样就够了。如果你的字符串里包含了变量,这个就不能用了。比如:

let count = 10
let says = NSLocalizedString("It runs \(count) times", comment: "run times")

says即使你翻译了,生成的程序也不能正确地显示。这是因为,目前版本的NSLocalizedString不支持Swift的这种用法。它先把says变成“It runs 10 times",然后查找是否有翻译与其匹配,显然是没有的。

在这里,我们需要使用StringlocalizedStringWithFormat方法。

let newSays = String.localizedStringWithFormat(NSLocalizedString("It runs %d times", comment: "new run times"), count)

然后就可以了。这么做很不Swift,但是,这个是目前唯一可用的办法。

注册`UserDefaults.didChangeNotification`的技巧

UserDefaults.didChangeNotification应该在PreferencesViewController里进行注册,而不是在需要变化的ViewController里。因为如果是在后者注册,程序运行时,可能会出现意想不到的异常。即用户在没有打开设置的情况下,设置变了,而造成你的程序的异常。

今天下午排查了很久,最后发现是这个原因。

URL的path相等,但是URL却可能不相等的问题

与预期的不同,URL即使path相同,URL也可能是不同的。因此,应避免使用init(fileURLWithPath: String, isDirectory: Bool, relativeTo: URL?),使用appendingPathComponent(_:isDirectory:)作为替代。

let url = URL(fileURLWithPath: "foo/bar", isDirectory: false)
let baseURL = url.deletingLastPathComponent()
let newURL = URL(fileURLWithPath: "bar", isDirectory: false, relativeTo: baseURL)
let testURL = baseURL.appendingPathComponent("bar")

print(url == newURL) // prints false
print(url.path == newURL.path) // prints true

print(url == testURL) // prints true
print(url.path == testURL.path) // prints true