Clearer
Clearer

Reputation: 2306

Unable to compile applescript from NSString

I've been trying to figure out how to run applescript in a objective-c program but so far haven't been able to.

Regardless of how I load the source into the NSAppleScript object, I simply can't get it to compile. Loading from a file returns a nil and loading from source just plain refuses to compile.

I am not an objective-c programmer in any respect and I am having a hard time figuring out how this brain dead language works. Any and all problems are likely correlated to my inability to comprehend why a constructor changes its name based on the arguments you give it.

Example source of one of my many attempts: (note, the script is correct and works fine in Script Editor)

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSString * source =
        @"to go_home()\n"
        "    tell application \"Finder\" to open \"Home\"\n"
        "end go_home\n"
        "go_home()";

        NSAppleScript * script = [[NSAppleScript alloc] initWithSource: source];

        if ( script == nil)
            NSLog(@"Script is nil");

        NSLog(@"Script source = %@", script.source);

        [script compileAndReturnError: nil];
        [script executeAndReturnError: nil];

        if ([script isCompiled])
            NSLog(@"Script is compiled");
        else
            NSLog(@"Script is not compiled");
    }
    return 0;
}

Example output:

2017-12-05 11:05:48.249206+0100 applescript[11826:744415] Script source = to go_home()
    tell application "Finder" to open "Home"
end go_home
go_home()
2017-12-05 11:05:48.262797+0100 applescript[11826:744415] Script is not compiled
Program ended with exit code: 0

Edit: It appears that the problem is related to XCode. When I compile the program in a terminal, everything works fine.

Upvotes: 0

Views: 232

Answers (1)

Sangram Shivankar
Sangram Shivankar

Reputation: 3573

i am getting Script is compiled Program ended with exit code: 0 for same code. you can check error by replacing

[script compileAndReturnError: nil];
[script executeAndReturnError: nil];

with

 NSDictionary *error;
 [script compileAndReturnError: &error];
 [script executeAndReturnError: &error];

Upvotes: 1

Related Questions