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
includingResourceValuesForKeys:nil
relativeToURL:nil
error:NULL];
[NSURL writeBookmarkData:bookmarkData
toURL:dest
options:0
error:NULL];

Isn’t that about a billion times easier?
I’m not sure what the relativeToURL: parameter is for yet; comments are welcome.

3 responses to “Creating a Finder alias programmatically on Snow Leopard”

  1. The relativeURL parameter can be used to resolve the file relative to the location of another file. Think of a mounted volume that can be mounted at different root locations, the full path of an item in the volume can be different when you look it up later, but the relative path to some base item may be preserved. Whether it actually works I do not know. I do know that in the Carbon Alias Manager the relative location just did not work: it was never able to find back files by relative paths when the full path had changed but the relative path remained the same.

    Like

  2. This comment has been removed by a blog administrator.

    Like

Leave a reply to Anonymous Cancel reply