Czy można wstępnie zdefiniować stałą lub zmienną dla AppleScript w aplikacji kakao? innymi słowy, czy można zdefiniować funkcję „addConstantToAppleScript” (użytą w poniższym kodzie)?
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];
dzięki.
Odpowiedzi:
0 dla odpowiedzi № 1Jeśli chcesz dodać NSDictionary
par klucz / wartość do początku NSString
zawierający AppleScript, możesz użyć czegoś takiego jak następująca funkcja. Osobiście zrobiłbym to jako kategorię na NSString, ale poprosiłeś o funkcję.
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];
}
Ta funkcja przekształca pary klucz / wartość w instrukcje AppleScript formularza set <key> to "<value>"
. Te instrukcje są następnie dodawane z przodu dostarczonego script
strunowy. Wynikowy ciąg skryptu jest następnie zwracany.
Można użyć powyższej funkcji w następujący sposób:
// Create a dictionary with two entries:
// myText = HellorWorld!
// Foo = Bar
NSDictionary *constants = [[NSDictionary alloc ] initWithObjectsAndKeys:@"HellorWorld!", @"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 "HellorWorld!"
// tell application "Finder" to display dialog myText
NSAppleScript *appleScript = [[NSAppleScript alloc] initWithSource:sourceScript];