在 AppleScript 中格式化本地化字符串的最佳方法是什么?

StackOverflow https://stackoverflow.com/questions/64146

  •  09-06-2019
  •  | 
  •  

当脚本保存为包时,它可以使用 localized string 命令查找适当的字符串,例如在 Contents/Resources/English.lproj/Localizable.strings. 。如果这是格式字符串,填充占位符的最佳方法是什么?换句话说,AppleScript 相当于什么 +[NSString stringWithFormat:]?

我的一个想法是使用 do shell scriptprintf(1). 。有没有更好的办法?

有帮助吗?

解决方案

自 OS X 10.10 起, ,任何 AppleScript 脚本都可以使用 Objective-C。有几种方法可以从 AppleScript 中调用 Objective-C 方法,详细信息请参见 本翻译指南. 。像我这样的 Objective-C 开发人员会倾向于这种语法,它将方法的参数与其值进行插值:

use framework "Foundation"

tell the current application's NSWorkspace's sharedWorkspace to openFile:"/Users/me/Desktop/filter.png" withApplication:"Preview"

结果:

true

+[NSString stringWithFormat:] 这是一个棘手的案件。它采用可变参数列表作为其第一个参数,因此您需要某种方法来强制将格式字符串及其参数放入同一方法参数中。以下结果会导致错误,因为 AppleScript 最终将单个 NSArray 传递到概念上需要 NSString 的 C 数组的参数中:

use framework "Foundation"

the current application's NSString's stringWithFormat:{"%lu documents", 8}

结果:

error "-[__NSArrayM length]: unrecognized selector sent to instance 0x7fd8d59f3bf0" number -10000

相反,您必须使用看起来更像 AppleScript 处理程序调用而不是 Objective-C 消息的替代语法。您还需要将返回值(一个 NSString 对象)强制转换为 text:

use framework "Foundation"

the current application's NSString's stringWithFormat_("%lu documents", 8) as text

结果:

"2087 documents"

@nlanza 提到的“带参数”语法指出 AppleScript 使用类似于 NS调用 在引擎盖下。在 Objective-C 中,NSInitation 允许您将消息以及参数值数组发送到对象,而不必将每个值与特定参数相匹配。(看 本文 有关直接使用 NSInitation 的一些示例。)

其他提示

尽管它很丑陋,但呼唤着 printf(1) 是常见的解决方案。

一个更干净但更复杂的解决方案是使用 AppleScript Studio,它允许您使用 AppleScript 代码调用 Objective-C 对象/类 call method 语法记录 这里.

这样,您就可以使用这样的东西:

call method "stringWithFormat:" of class "NSString" with parameters {formatString, arguments}

当然,这样做的缺点是您需要编写一个 AppleScript Studio 应用程序,而不仅仅是编写一个简单的脚本。不过,总体而言,使用 Studio 应用程序确实可以获得更大的灵活性,因此这并不是一条糟糕的道路。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top