简体   繁体   中英

How do I create an FSRef from a NSString containing a path?

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?

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");
}

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()

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM