I'm having an issue with opening directories that have spaces in them. My code looks like this:
NSOpenPanel* openDlg = [NSOpenPanel openPanel];
[openDlg setCanChooseDirectories:YES];
if ( [openDlg runModal] == NSOKButton )
{
NSArray* files = [openDlg URLs];
NSString* directoryName = [[files objectAtIndex:0] absoluteString];
directoryURL = [files objectAtIndex:0];
NSLog(@"Directory Name: %@", directoryName);
NSArray *directoryArray = [directoryName componentsSeparatedByString:@"/"];
NSString* currentDirectory = [directoryArray objectAtIndex:(directoryArray.count- 2)];
[directoryBox setTitle:currentDirectory];
}
When I select a directory name with spaces the files are not displayed in a table and the output in the NSLog looks like this:
Directory Name:
file://localhost/Users/Rich/Software%20Bisque/
Any ideas?
The -URLs
method of of NSOpenPanel
returns instances of NSURL
, not file system paths. While NSURL
s have become the preferred way to refer to files, you can easily change to a file system path by using NSURL
's -path
method.
Note that there are many methods specific to working with file system paths that are added to NSString
in NSPathUtilities.h
. You could probably rewrite your code to incorporate those (double-check that I've got your targeted directory okay):
NSArray* files = [openDlg URLs];
NSString* directoryName = [[files objectAtIndex:0] path];
directoryURL = [files objectAtIndex:0];
NSLog(@"Directory Name: %@", directoryName);
// NSArray *directoryArray = [directoryName pathComponents];
// NSString* currentDirectory = [directoryArray objectAtIndex:(directoryArray.count- 2)];
NSString *currentDirectory = [[directoryName stringByDeletingLastPathComponent]
lastPathComponent];
[directoryBox setTitle:currentDirectory];
You could try removing the percent escapes in the directoryName
string - I don't think the system needs them there. Something like:
directoryName = [directoryName stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
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.