Applescript from within Cocoa

So, I wanted to query iTunes from within a Cocoa-App for all of its playlists. Sounds simple, doesn’t it? And telling iTunes to start playing must be even simpler, or not?

Of course, you could do this quit simple:
– Get the path of the iTunes Library
– Parse the iTunes Library.xml for playlist entries
– use osascript(1) to tell iTunes to start playing the playlist.
Simple as that. But heck – somehow this does not really look satisfying. Parsing another app’s Property List and Library? Going to shell to execute Applescript? Pleeeease…

Next Step: Let’s check the API for Apple Events
e Events. Hummm. Stranded in Carbon? Yup: No classes, no easy-understood-easy-used methods – plain obfuscated C. Nonononono.

OK, another way: Using Foundation’s NSAppleScript, a nice wrapper for the API. But wait: Why is it necessary to write 10 or more lines for a simple query? And why do we find ourselves in pure ugly C-Code after Line 5? Nope, not what I was looking for.

What I really want is a handle, which I can connect to an app, and then just posting a Message and retrieve the result. As far as I can see, there is nothing which would provide some simple of use within an OO construct. Sounds like a job for a Student on holiday… Enter APApplescriptHandler

APApplescriptHandler * iTunes = [[APApplescriptHandler alloc] initWithApplicationName:@“iTunes“];
[iTunes performMessage:@“playpause“];
NSString * string = [iTunes getStringForMessage:@“name of current track“];
NSArray * array = [iTunes getArrayOfStringsForMessage:@“

ApplescripHandler; Interface; Implementation
This is one of my first things done in Objective-C – so the Code most probably stinks for any experienced Programmer. I sure hope it will stink for me too in some months. But experienced Coders most propably won’t have any use for this class, and for newbies it will work and look just fine. Just be sure to catch the NSException if you use getArrayOfStringsForMessage: with a Message, which does not return a list. Every other Error I could think of is treated internally and results in a returning nil.
Any feedback is very welcome.