从Cocoa应用程序运行Applescript [英] Running Applescript from a Cocoa application
问题描述
我想在可可应用程序中运行一个简单的applescript。我读了关于这个问题的苹果文档,但它是太混乱了我(初学者)来理解。
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
推荐答案
根据文档中,您可以使用 NSAppleScript 类。
Per the documentation, you use the NSAppleScript class.
这个非常简短的API引用有一个叫做初始化脚本的部分,其中一个方法是 -initWithSource:
,它接受一个NSString。
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.
一旦你有了脚本对象,你就可以 -compileAndReturnError:
然后 -executeAndReturnError:
作为单独的步骤,或者只是 -executeAndReturnError:
,根据该方法的文档 - 如果尚未编译源代码,则尝试编译源代码,然后执行。
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.
注意,NSAppleScript只能从主线程执行的警告(alloc,init ...,autorelease,executeAndReturnError :)如果你忽略错误, (即不是来自NSOperation / Queue或其他线程)。
Note the warning that NSAppleScript can only be executed from the main thread (ie, not from an NSOperation/Queue or other threads).
这篇关于从Cocoa应用程序运行Applescript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!