如何预定义Applescript常量或变量

时间:2012-05-02 08:27:24

标签: macos cocoa applescript

是否可以在cocoa应用程序中为AppleScript预定义常量或变量? 换句话说,函数“addConstantToAppleScript”(在下面的代码中使用)是可定义的吗?

addConstantToAppleScript("myText", "Hello!");
char *src = "display dialog myText";
NSString *scriptSource = [NSString stringWithCString:src]; 
NSAppleScript *appleScript = [[NSAppleScript alloc] initWithSource:scriptSource];
NSDictionary *scriptError = [[NSDictionary alloc] init];
[appleScript executeAndReturnError:scriptError];

感谢。

1 个答案:

答案 0 :(得分:0)

如果要将NSDictionary个键/值对添加到包含AppleScript的NSString的开头,可以使用类似以下功能的内容。就个人而言,我会将此作为NSString的一个类别,但你已经要求一个函数。

NSString *addConstantsToAppleScript(NSString *script, NSDictionary *constants) {
    NSMutableString *constantsScript = [NSMutableString string];

    for(NSString *name in constants) {
        [constantsScript appendFormat:@"set %@ to \"%@\"\n", name, [constants objectForKey:name]];
    }   

    return [NSString stringWithFormat:@"%@%@", constantsScript, script];
}

此函数将键/值对转换为set <key> to "<value>"形式的AppleScript语句。然后将这些语句添加到提供的script字符串的前面。然后返回生成的脚本字符串。

您可以按如下方式使用上述功能:

// Create a dictionary with two entries:
//     myText = Hello\rWorld!
//     Foo    = Bar
NSDictionary *constants = [[NSDictionary alloc ] initWithObjectsAndKeys:@"Hello\rWorld!", @"myText", @"Bar", @"Foo", nil];

// The AppleScript to have the constants prepended to   
NSString *script = @"tell application \"Finder\" to display dialog myText";

// Add the constants to the beginning of the script 
NSString *sourceScript = addConstantsToAppleScript(script, constants);

// sourceScript now equals
//     set Foo to "Bar"
//     set myText to "Hello\rWorld!"
//     tell application "Finder" to display dialog myText

NSAppleScript *appleScript = [[NSAppleScript alloc] initWithSource:sourceScript];