1

是否可以在可可应用程序中为 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];

谢谢。

4

1 回答 1

0

如果您想在包含 AppleScriptNSDictionary的开头添加一个键/值对,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];
}

此函数将键/值对转换为形式的 AppleScript 语句set <key> to "<value>"。然后将这些语句添加到提供的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];
于 2012-05-02T08:34:17.660 回答