Friday, August 28, 2009

Creating a Finder alias programmatically on Snow Leopard

My co-worker Dan posted a blog yesterday entitled "How to Create an Alias Programmatically". His example is 21 lines long, and is compatible with Leopard and earlier. It only works if the original item is a folder (though creating an alias to a file is not much different). The code messes with resource forks, and the C interface is generally difficult to read for someone who spends most of their time in Objective-C. The code is also not guaranteed to be 100% accurate, since Apple explicitly did not support programmatic alias creation in Leopard.

This is a great example of how Apple has improved the developer experience for OS X in Snow Leopard. Snow Leopard contains some new APIs for "bookmark" creation, which appears to be the new behind-the-scenes name for aliases. The following four lines of code create a functioning alias on Snow Leopard:

NSURL *src = [NSURL URLWithString:@"file:///Users/bjh/Desktop/temp.m"];
NSURL *dest = [NSURL URLWithString:@"file:///Users/bjh/Desktop/myalias"];

NSData *bookmarkData = [src bookmarkDataWithOptions:NSURLBookmarkCreationSuitableForBookmarkFile
[NSURL writeBookmarkData:bookmarkData

Isn't that about a billion times easier?

I'm not sure what the relativeToURL: parameter is for yet; comments are welcome.