xcode NSOpenPanel 在 Objective-C 中获取文件名?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11815784/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
NSOpenPanel get filename in Objective-C?
提问by user1568364
When I create an NSOpenPanel, like this:
当我创建一个 NSOpenPanel 时,像这样:
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?
当我登录时fileName
,它是正确的并打印我的文件完整目录,但是当我尝试将它与我的 void 一起使用时,它变得像超级奇怪的字母,就像 ?^0f 完全随机。为什么?
回答by zpasternack
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?
该代码没有任何问题。实际上,该代码有许多不太理想的地方,但没有什么可以使它不起作用。decompresss2z: 函数是什么样的?
If this were my code, I'd make the following changes:
如果这是我的代码,我会进行以下更改:
runModalForDirectory:file:
is deprecated; you should userunModal
instead.filenames
is deprecated; you should useURLs
instead (you can callpath
on each URL to get the filename).NSLog
's parameter needs to be a format string, or else odd things can happen.- 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). - There's no reason to call
performSelector:withObject:
here; just call the method normally.
runModalForDirectory:file:
已弃用;你应该runModal
改用。filenames
已弃用;您应该URLs
改用(您可以调用path
每个 URL 来获取文件名)。NSLog
的参数必须是格式字符串,否则可能会发生奇怪的事情。- 您应该使用快速枚举(使用
in
关键字),而不是遍历带有索引的容器。它不仅效率更高,而且代码更少(代码越少越好)。 - 没有理由在
performSelector:withObject:
这里打电话;只需正常调用该方法。
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.
不过,这些更改都不会改变您的实际问题。为了进一步提供帮助,我们需要查看更多代码。具体来说,我想看看 decompressss2z: 是什么样的。