问题
I want to run a simple applescript in a cocoa application. I read the apple documentation on the matter but it was too confusing for me (a beginner) to understand.
tell application "iTunes" to play
回答1:
Per the documentation, you use the NSAppleScript class.
The very short API reference has a section called "Initializing a Script," one method of which is -initWithSource:
, which takes an NSString. You'll create your object this way.
Once you have your script object, you can then either -compileAndReturnError:
then -executeAndReturnError:
as separate steps, or just -executeAndReturnError:
, which - according to the documentation for that method - tries to compile the source first if it's not been already, then executes.
So, in theory, you could probably do all this in one line. (alloc, init..., autorelease, executeAndReturnError:) if you ignore errors like a naughty developer.
Note the warning that NSAppleScript can only be executed from the main thread (ie, not from an NSOperation/Queue or other threads).
来源:https://stackoverflow.com/questions/3213895/running-applescript-from-a-cocoa-application