2008-01-21 01:51:13 Volume respect category for NSFileManager
It came up in #macdev that if NSFileManager's -fileExistsAtPath: method is given the path of a symbolic link on a remote mounted volume (/Volume/ForeignDrive/some/file/symlink), and let's say that it points to a file that exists (as seen on this machine) at /Volume/ForeignDrive/real/file, it will respond with a yes/no response that corresponds to the existence of a file at /real/file on the local drive, which very well might not exist, and in some cases would exist only by sheer coincidence. This is the symlink way, which merely contains a reference to the file in the form of a string that says, "/real/file."

Here's a diagram, since that might have been confusing:

This answer, which makes its own convoluted sense in some cases, doesn't help me if I want to get an answer to the question of the file's existence as pointed to by the symlink on the remote machine. What I want to know is: does the file /Volume/ForeignDrive/real/file exist?

At any rate, I added a category to NSFileManager that does just that:
( objc )
  1  @interface NSFileManager ( HJFileManager )
2 -(BOOL)fileExistsAtPath:(NSString *)path respectVolumeSymbolicLink:(BOOL)respect;
3 @end
5 @implementation NSFileManager ( HJFileManager )
6 -(BOOL)fileExistsAtPath:(NSString *)path respectVolumeSymbolicLink:(BOOL)respect {
8 if (respect && [path hasPrefix:@"/Volumes/"]) {
10 NSString *pathContent = [self pathContentOfSymbolicLinkAtPath:path];
11 if ([pathContent hasPrefix:@"/"])
13 return [self fileExistsAtPath:
14 [[@"/Volumes"
15 stringByAppendingPathComponent:[[path pathComponents] objectAtIndex:2]]
16 stringByAppendingPathComponent:pathContent]];
18 }
19 return [self fileExistsAtPath:path];
20 }
21 @end

Enjoy in good health if you find it useful.
  • Jeff (Mon, January 21st, 2008, 4:48pm UTC)
    I have to give props to Rainer for once again helping make this code much better than it started out, and helping me chase down weird test cases.

Leave a comment