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;
@end

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, 
												 (CFStringRef)aliasPath, 
												 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);
					CFRelease(resolvedUrl);
				}
			}
		}
		CFRelease(url);
	}
	
	// If not resolved, just pass the aliasPath
	if (resolvedPath == nil)
	{
		resolvedPath = [[NSString alloc] initWithString:aliasPath];
	}
	
	return [resolvedPath autorelease];
}
@end
About these ads

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 49 other followers

%d bloggers like this: