1

我正在尝试制作一个询问用户目录的 Mac OS X 应用程序。我正在使用当用户按下“浏览”按钮时触发的 NSOpenPanel。

问题是,[NSOpenPanel filenames] 已被弃用,所以现在我正在使用 URLs 函数。我想解析出与获取正常文件路径相关的 url 的东西。所以我尝试fileName = [fileName stringByReplacingOccurrencesOfString:@"%%20" withString:@" "];了,但这给了我一个错误:

-[NSURL stringByReplacingOccurrencesOfString:withString:]: unrecognized selector sent to instance 0x100521fa0

这是整个方法:

- (void) browse:(id)sender
{
    int i; // Loop counter.

    // Create the File Open Dialog class.
    NSOpenPanel* openDlg = [NSOpenPanel openPanel];

    // Enable the selection of files in the dialog.
    [openDlg setCanChooseFiles:NO];

    // Enable the selection of directories in the dialog.
    [openDlg setCanChooseDirectories:YES];

    // Display the dialog.  If the OK button was pressed,
    // process the files.
    if ( [openDlg runModal] == NSOKButton )
    {
        // Get an array containing the full filenames of all
        // files and directories selected.
        NSArray* files = [openDlg URLs];

        // Loop through all the files and process them.
        for( i = 0; i < [files count]; i++ )
        {
            NSString* fileName = (NSString*)[files objectAtIndex:i];
            NSLog(@"%@", fileName);

            // Do something with the filename.
            fileName = [fileName stringByReplacingOccurrencesOfString:@"%%20" withString:@" "];

            NSLog(@"%@", fileName);
            NSLog(@"Foo");
            [oldJarLocation setStringValue:fileName];
            [self preparePopUpButton];
        }
    }
}

有趣的是,“Foo”永远不会被输出到那个控制台。就像方法在 stringByReplacigOccurencesOfString 行中止一样。

如果我删除那一行,应用程序将运行并用我不想要的 URL 形式的字符串填充我的文本框。

4

1 回答 1

1

您的问题是NSArray返回的[NSOpenPanel URLs]包含NSURL对象,而不是NSString对象。你正在做以下演员:

 NSString* fileName = (NSString*)[files objectAtIndex:i];

由于NSArray返回一个. id_NSStringNSURL

可以NSURL对象转换为NSString并按原样使用您的代码,但您无需自己处理 URL 解码。NSURL已经有一种检索路径部分的方法,该方法也撤消了百分比编码:path

NSString *filePath = [yourUrl path];

即使您的代码处理 percent-encoded NSString,也有stringByReplacingPercentEscapesUsingEncoding:.

于 2011-10-10T01:59:39.073 回答