我在打开包含空格的目录时遇到问题。我的代码如下所示:
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];
}
当我选择带空格的目录名时,文件不会显示在表中,NSLog中的输出如下所示:
目录名称:
file://localhost/Users/Rich/Software%20Bisque/
有什么想法吗?
答案 0 :(得分:4)
NSOpenPanel
的{{3}}方法返回NSURL
的实例,而不是文件系统路径。虽然NSURL
已成为引用文件的首选方式,但您可以使用NSURL
的{{3}}方法轻松更改为文件系统路径。
请注意,有许多特定方法可用于处理NSString
中添加到NSPathUtilities.h
的文件系统路径。您可能会重写您的代码以合并它们(仔细检查我的目标目录是否正常):
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];
答案 1 :(得分:1)
您可以尝试删除directoryName
字符串中的百分比转义 - 我认为系统不需要它们。类似的东西:
directoryName = [directoryName stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];