Resolving aliases using Cocoa?

Alias is more common than link on a Mac OS X to most users. They can make aliases easily from the Finder.
However, the NSFileManager doesn’t have any method for manipulating aliases. It can handles symbolic links only.

Then, how to handle aliases? If you implement Drag&Drop, you would need to resolve aliases. The only one option is to get help from Core Foundation.

The “Resolving aliases” section of “Low-Level File Management Programming Topics” shows full implementation for this. I would like to add a few more lines to make it as an extension to the NSFileManager.

A header file : NSFileManager_AliasExt.h

@interface NSFileManager (NSFileManager_AliasExt)
- (NSString *)identifyOriginalPath:(NSString *)aliasPath;

An implementation file : NSFileManager_AliasExt.m

#import "NSFileManager_AliasExt.h"

@implementation NSFileManager (NSFileManager_AliasExt)

- (NSString *)identifyOriginalPath:(NSString *)aliasPath
	NSString *resolvedPath = nil;
	CFURLRef url = CFURLCreateWithFileSystemPath( kCFAllocatorDefault, 
												 kCFURLPOSIXPathStyle, NO);
	if (url != NULL)
		FSRef fsRef;
		if (CFURLGetFSRef(url, &fsRef))
			Boolean targetIsFolder, wasAliased;
			OSErr err = FSResolveAliasFile (&fsRef, true, &targetIsFolder, &wasAliased);
			if ((err == noErr) && wasAliased)
				CFURLRef resolvedUrl = CFURLCreateFromFSRef(kCFAllocatorDefault, &fsRef);
				if (resolvedUrl != NULL)
					resolvedPath = (NSString*)CFURLCopyFileSystemPath(resolvedUrl, kCFURLPOSIXPathStyle);
	// If not resolved, just pass the aliasPath
	if (resolvedPath == nil)
		resolvedPath = [[NSString alloc] initWithString:aliasPath];
	return [resolvedPath autorelease];

One response to this post.

  1. […] I’m not able to get @Milliways’s solution working (knowing nothing about Cocoa) and stuff I find elsewhere on the internet looks far more complicated (perhaps it’s handling all kinds of edge […]


Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: