问题
I would like to pass a variable to applescript. For example, I type some words in textfield of a Cocoa-App (not cocoa-applescript app).Then, it will be a variable in Applescript for future use. I use Applescript to tell some software to run some files.
I've tried How Can I Pass a String From Applescript to Objective C the method here. It could add the first lines in applescript using initialwithSource. I have to write a long sentence. Also if I've already have the applescript, I have to either combine them together. Or I have to write all the script in Cocoa like below. It's meaningless and sometimes it doesn't work well.
NSString *SlideURL = [NSString stringWithFormat:@"set mypath to \"%@\" \n tell application \"Keynote\" \n open mypath \n tell slideshow %@ \n start slideshow\n end tell \n end tell\n",temp,temp];
// here is meaningless right
// temp is the variable I want to pass to applescript
NSDictionary *errorInfo = nil;
NSAppleScript *script = [[NSAppleScript alloc] initWithSource:SlideURL];
[script executeAndReturnError:&errorInfo];
[script release];
Do anyone of you know a better way ?
Thanks
回答1:
String mashing is evil. Just use AppleScriptObjC; there's no magic or complexity to it.
Assuming your application is built using the Cocoa Application template, you will need to 1. include the AppleScriptObjC framework in your project and 2. modify its main.m to match the ASOC template's main.m, which contains two extra lines:
#import <Cocoa/Cocoa.h>
#import <AppleScriptObjC/AppleScriptObjC.h>
int main(int argc, char *argv[])
{
[[NSBundle mainBundle] loadAppleScriptObjectiveCScripts];
return NSApplicationMain(argc, (const char **)argv);
}
Once you've done that, you can add ASOC-style script object files to your project and they'll look just like native classes to the rest of your ObjC program, e.g.:
-- FooTest.applescript
script FOOTest
property parent : class "NSObject"
on doSomething_(sender)
display dialog "Hello World"
end
end script
See this answer for useful links.
来源:https://stackoverflow.com/questions/16529800/pass-variable-or-string-from-os-x-cocoa-app-to-applescript