NSOpenPanel get filename in Objective-C?

。_饼干妹妹 提交于 2019-12-09 23:33:51

问题


When I create an NSOpenPanel, like this:

int i;

NSOpenPanel* openDlg = [NSOpenPanel openPanel];
[openDlg setCanChooseFiles:YES];
[openDlg setCanChooseDirectories:YES];

if ([openDlg runModalForDirectory:nil file:nil] == NSOKButton)
{
    NSArray* files = [openDlg filenames];

    for( i = 0; i < [files count]; i++ )
    {
        NSString* fileName = [files objectAtIndex:i];
        NSLog(fileName);
        NSString *catched = fileName;
        [self performSelector:@selector(decompresss2z:) withObject:catched];
    }
}

And when I log fileName, it is correct and prints my file full directory, but when I try to use it with my void, it gets like super weird letters, like ÿ^0f totally random. Why?


回答1:


There's nothing wrong with that code. Actually, there are a number of things that are less than ideal about that code, but nothing that will make it not work. What does the decompresss2z: function look like?

If this were my code, I'd make the following changes:

  1. runModalForDirectory:file: is deprecated; you should use runModal instead.
  2. filenames is deprecated; you should use URLs instead (you can call path on each URL to get the filename).
  3. NSLog's parameter needs to be a format string, or else odd things can happen.
  4. You should use fast enumeration (with the in keyword), rather than looping through a container with an index. It's not only more efficient, it's less code (and less code is better).
  5. There's no reason to call performSelector:withObject: here; just call the method normally.

Rewritten, it would look like this:

NSOpenPanel* openDlg = [NSOpenPanel openPanel];
[openDlg setCanChooseFiles:YES];
[openDlg setCanChooseDirectories:YES];

if ( [openDlg runModal] == NSOKButton )  // See #1
{
    for( NSURL* URL in [openDlg URLs] )  // See #2, #4
    {
        NSLog( @"%@", [URL path] );      // See #3
        [self decompresss2z:[URL path]]; // See #5
    }
}   

Again, though, none of these changes will change your actual issue. In order to help further, we need to see more code. Specifically, I'd like to see what decompressss2z: looks like.



来源:https://stackoverflow.com/questions/11815784/nsopenpanel-get-filename-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!