带空格的OSX目录

时间:2012-08-23 15:55:24

标签: objective-c macos file-io directory

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

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/

有什么想法吗?

2 个答案:

答案 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];