views:

73

answers:

1

I want to run a simple applescript in a cocoa application. I read the apple documentation on the matter but it was too confusing for me (a beginner) to understand.

tell application "iTunes" to play
+1  A: 

Per the documentation, you use the NSAppleScript class.

The very short API reference has a section called "Initializing a Script," one method of which is -initWithSource:, which takes an NSString. You'll create your object this way.

Once you have your script object, you can then either -compileAndReturnError: then -executeAndReturnError: as separate steps, or just -executeAndReturnError:, which - according to the documentation for that method - tries to compile the source first if it's not been already, then executes.

So, in theory, you could probably do all this in one line. (alloc, init..., autorelease, executeAndReturnError:) if you ignore errors like a naughty developer.

Note the warning that NSAppleScript can only be executed from the main thread (ie, not from an NSOperation/Queue or other threads).


Joshua Nozzi
so heres my script object/code.NSAppleScript *ascript = [[NSAppleScript alloc]init];[ascript executeAndReturnError:]how do i tell it what my script is
i dont see what im doing wrong. i dont know how to fill the argument after executeAndReturnError:this is literally my third day of objective c.
Hint: "-init" vs. "-initWithSource:".As for "filling in the argument," see: http://developer.apple.com/mac/library/referencelibrary/GettingStarted/Learning_Objective-C_A_Primer/ and http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/OOP_ObjC/Introduction/Introduction.html
Joshua Nozzi
OK i've came up with this. But it doesn't seem to run the script because it doesnt play or pause my itunes.-(IBAction)playpause:(id)sender{ NSAppleScript *playScript; playScript = [[NSAppleScript alloc] initWithSource:@"iTunesPlayPause.scpt"]; [playScript executeAndReturnError:nil];}
WHOOOOOOOOO!! i got it!!!!! initWithSource:@"" i should have put the applescript raw code. man i feel so accomplished.
@shorty876: the parameter of the method is not the name of the file containing the source code, but the string containing the code.
kiamlaluno