2

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

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

4

2 回答 2

2

从 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 传递到参数中,从概念上讲,该参数需要 NSStrings 的 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"

The “with parameters” syntax that @nlanza mentions points to the fact that AppleScript is using something akin to NSInvocation under the hood. In Objective-C, NSInvocation allows you to send a message to an object, along with an array of parameter values, without necessarily matching each value to a particular parameter. (See this article for some examples of using NSInvocation directly.)

于 2016-12-31T04:57:48.463 回答
0

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

一个更简洁但更复杂的解决方案是使用 AppleScript Studio,它允许您使用此处call method记录的语法从 AppleScript 代码调用 Objective-C 对象/类。

有了这个,你就可以使用这样的东西:

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

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

于 2008-09-15T20:58:52.517 回答