views:

282

answers:

3

I couldn't find a convenient way to create an alias, so I went with a symlink. I'm worried that that might not be good enough. Maybe the icon doesn't show on some versions of OS X or something like that.

[[NSFileManager defaultManager] createSymbolicLinkAtPath:aliasPath withDestinationPath:destPath error:nil];

Is this sort of thing the best I can do? http://www.danandcheryl.com/2009/08/how-create-alias-programmatically

+7  A: 

The answer depends on if you're using OS X 10.5 or 10.6. In 10.6, the old AliasManger has been replaced by NSURL's bookmark data. To create an alias, given an NSURL instance:

NSURL *url = [NSURL fileURLWithPath:pathToAliasTarget];
NSError *err = nil;
NSData *bookmarkData = [url bookmarkDataWithOptions: NSURLBookmarkCreationSuitableForBookmarkFile includingResourceValuesForKeys:nil relativeToURL:nil error:&err];

if(bookmarkData == nil) {
  //handle NSError in err
} else {
  if(![NSURL writeBookmarkData:bookmarkData toURL:aliasFileURL options:NSURLBookmarkCreationSuitableForBookmarkFile error:&err]) {
    //handle NSError in err
  }
}

As Peter Hosey points out, the bookmark data written using the NSURL API is not compatible with AliasManager routines. If you must support OS X < 10.6, you'll have to use the Carbon AliasManager API directly, or one of the Objective-C wrappers. I like Wolf Renstch's branch of BDAlias, available here.

Barry Wark
Bookmark data is not an alias. If you pass that data or a bookmark file to the Alias Manager, the Alias Manager will turn up its nose at it.
Peter Hosey
(Which implies that if you take a bookmark file to a machine running Leopard or earlier, it won't work.)
Peter Hosey
@Peter, I wasn't aware that bookmark data wasn't interchangeable with AliasManager aliases. Thanks for the pointer. Feel free to edit the post appropriately. I guess this makes the case for `BDAlias` or something similar much stronger if you have to support OS X < 10.6.
Barry Wark
+2  A: 

To create an alias, take a look at NDAlias, at http://www.cocoadev.com/index.pl?NDAlias

Jon
That looks good. Unfortunately, I can't use it for above me licensing reasons, but fortunately symlinks appear good enough for my case.
zekel
+1  A: 

I've also found this blog post to be excellently useful: http://www.danandcheryl.com/2009/08/how-create-alias-programmatically

Dave DeLong