3

我在打开包含空格的目录时遇到问题。我的代码如下所示:

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/

有任何想法吗?

4

2 回答 2

4

-URLs方法NSOpenPanel返回 的实例NSURL,而不是文件系统路径。虽然NSURLs 已成为引用文件的首选方式,但您可以使用NSURL'-path方法轻松更改为文件系统路径。

请注意,有许多特定于处理文件系统路径的方法,这些路径添加NSStringNSPathUtilities.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];
于 2012-08-23T16:25:19.693 回答
1

您可以尝试删除字符串中的百分比转义directoryName- 我认为系统不需要它们。就像是:

directoryName = [directoryName stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
于 2012-08-23T16:00:27.423 回答