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.
一些侦查工作之后我发现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 Apple.com documentation searches could tell me:NSWorkspaceis the Cocoa equivalent of LaunchServices.
With that piece of knowledge everything fell together. Looking atthe documentation for NSWorkspaceit turns out that *openFile:(NSString *)aPath* provided the functionality that I needed.
Using it is quite simple:
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 toopenFileis aNSStringcontaining the filepath to the file you want to open.
This is just one example of my Cocoa development motto: Once you know, itstrivial. Before you know, itsimpossible. Bridging that gap falls betweentrivialandimpossible, skewed towards the extremes.