如果您想在包含 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];