Search code examples
macoscocoaapplescriptapplescript-objcnsworkspace

Using Cocoa with AppleScript


Having some trouble calling Cocoa methods from within AppleScript. For example, running the following snippet of code produces an error when ran using osascript:

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

Here's the thrown exception: Expected “,” but found identifier. (-2741) Should this code be nested under a tell statement? If so, what application should I be talking to?

Thanks.


Solution

  • call method looks like something out of the old AppleScript Studio, which was deprecated in 10.6 Snow Leopard and has since been removed.

    There are a couple of prerequisites for calling Cocoa methods - a regular script needs to declare that it uses the desired framework(s), and the various classes and enums are defined at the application level and thus need to be prefaced with current application, or an object needs to exist to send the message to.

    With that said, Cocoa methods can be called in a few different ways - using your snippet, for example:

    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
    

    The first form is what you will normally see used, as it is the closest to the Objective-C form. The appendix in the Mac Automation Scripting Guide has more information about translating from the Objective-C documentation, which is what Apple expects you to use.