views:

457

answers:

3

I have a file system path in a NSString, but I need an FSRef for the system call I will be making. What is the best way to create the FSRef?

+4  A: 

Try FSPathMakeRef:

NSString *path = @"Some... path... here";
FSRef f;
OSStatus os_status = FSPathMakeRef((const UInt8 *)[path fileSystemRepresentation], &f, NULL);

if (os_status == noErr) {
    NSLog(@"Success");
}
Jarret Hardie
+1  A: 

You can use FSPathMakeRef() to make an FSRef from a UTF-8 C string path, and you can use the -UTF8String method of NSString to get a UTF-8 C string:

FSRef fsref;
Boolean isDirectory;
OSStatus result = FSPathMakeRef([myString UTF8String], &fsref, &isDirectory);
if(result < 0)
    // handle error
// If successful, fsref is valid, and isDirectory is true if the given path
// is a directory.  If you don't care about that, you can instead pass NULL
// for the third argument of FSPathMakeRef()
Adam Rosenfield
A: 

You can use this method from Nathan Day in his an NSString+NDCarbonUtilities category:

- (BOOL)getFSRef:(FSRef *)aFSRef
{
    return FSPathMakeRef( (const UInt8 *)[self fileSystemRepresentation], aFSRef, NULL ) == noErr;
}

See NDAlias at http://homepage.mac.com/nathan_day/pages/source.xml for more (MIT Licensed).

Peter N Lewis