在 AppleScript 中使用 Cocoa

Using Cocoa with AppleScript

从 AppleScript 中调用 Cocoa 方法时遇到一些问题。例如,运行 当 运行 使用 osascript 时,以下代码片段会产生错误:

set sharedWorkspace to call method "sharedWorkspace" of class "NSWorkspace"

这里是抛出的异常:Expected “,” but found identifier. (-2741)这段代码应该嵌套在 tell 语句下吗?如果是这样,我应该与哪个应用程序通话?

谢谢。

这应该有效:

set sharedWorkspace to current application's NSWorkspace's sharedWorkspace()

call method 看起来像是旧的 AppleScript Studio 中的东西,它在 10.6 Snow Leopard 中被弃用并已被删除。

调用 Cocoa 方法有几个先决条件 - 常规脚本需要声明它使用所需的框架,并且各种 类 和枚举在应用程序级别,因此需要以 current application 开头,或者需要存在一个对象才能将消息发送到。

也就是说,Cocoa 方法可以通过几种不同的方式调用 - 使用您的代码片段,例如:

use framework "Foundation"

set sharedWorkspace to current application's NSWorkspace's sharedWorkspace
-- or --
set sharedWorkspace to sharedWorkspace of current application's NSWorkSpace
-- or --
tell current application's NSSharedWorkspace's sharedWorkspace
    set sharedWorkspace to it
end tell

第一种形式是您通常会看到的形式,因为它最接近 Objective-C 形式。 Mac Automation Scripting Guide 中的附录包含有关从 Objective-C 文档翻译的更多信息,这是 Apple 希望您使用的内容。