I need to run some AppleScript from a Cocoa app. I am using the following code:
void doAppleScript (NSString* ASString)
{
NSAppleScript* script = [[NSAppleScript alloc] initWithSource];
NSDictionary* errorInfo = [NSDictionary dictionary];
NSAppleEventDescriptor* descriptor = [script executeAndReturnError:&errorInfo];
[script release];
if (descriptor == nil) { // there was a compile error
NSString* error = [errorInfo objectForKey:NSAppleScriptErrorMessage];
NSLog(@“doAppleScript error = %@”, error); NSBeep();
}else{ // script compiled and ran with no errors
NSLog(@“doAppleScript successful with script = %@”, ASString);
}
}
This works great for most scripts, but fails with an NSReceiverEvaluationScriptError: 4 in some cases. The problem seems to be with referenced UI elements that are not found, such as:
“tell application "System Events" to click radio button "off" of radio group 1 of group 3 of window "Controller Window" of application process "myApp"”
Odd thing is that the same script (without the quote or new line escapements) compiles and runs just fine from Script Editor (or Script Debugger 4 or the Script Menu), so I know the AppleScript code and the references to the UI elements are good.
Much thanks for any ideas on how to debug…