Opening Files With Associated App in Cocoa

April 5, 2008. Filed under cocoa 13 objc 8

While working on a current project written in Cocoa and Objective C I came onto a portion where I needed to open files, but I didn't know what application I wanted to open them with. I wanted to recreate the effect of double clicking on a file in finder (which opens the file based on your chosen application for the given file extension), and fortunately that is quite easy to do.

After a bit of sleuthing I discovered that in Carbon that effect was achieved using LaunchServices, but shortly thereafter I discovered that LaunchServices does not exist in Cocoa. I spent a while looking for the Cocoa equivalent, and was getting a bit frustrated in my failure. I was about to surrender myself to including the Carbon framework in my Cocoa application, but decided to give it one last try: I was pretty certain that Cocoa did have an equivalent, I just wasn't sure where the hell it was hidden.

Reading through the Cocoa overview I found what neither Google nor documentation searches could tell me: NSWorkspace is the Cocoa equivalent of LaunchServices.

With that piece of knowledge everything fell together. Looking at the documentation for NSWorkspace it turns out that *openFile:(NSString *)aPath* provided the functionality that I needed.

Using it is quite simple:

NSString *aFilePath = [someFiles objectAtIndex:0];
NSWorkspace *workspace = [NSWorkspace sharedWorkspace];
[workspace openFile:aFilePath];

Notice that the code uses [NSWorkspace sharedWorkspace] instead of the standard Objective C paradigm along the lines of [[NSWorkspace alloc] init]. This is because there is a shared global workspace which you can use instead of allocating and initializing a new one. The biggest gain is that you don't have to (to be more precise, must not) release it after you are finished using it. The argument to openFile is a NSString containing the filepath to the file you want to open.

This is just one example of my Cocoa development motto: Once you know, its trivial. Before you know, its impossible. Bridging that gap falls between trivial and impossible, skewed towards the extremes.