NSOpenPanel 在 Objective-C 中获取文件名? [英] NSOpenPanel get filename in Objective-C?
问题描述
当我创建一个 NSOpenPanel 时,像这样:
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];
}
}
当我登录 fileName
时,它是正确的并打印我的文件完整目录,但是当我尝试将它与我的 void 一起使用时,它变得像超级奇怪的字母,就像 ÿ^0f 完全随机.为什么?
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?
推荐答案
该代码没有任何问题.实际上,该代码有许多不太理想的地方,但没有什么可以使它不起作用.decompresss2z: 函数是什么样的?
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:
runModalForDirectory:file:
已弃用;你应该使用runModal
代替.filenames
已弃用;您应该改用URLs
(您可以在每个 URL 上调用path
以获取文件名).NSLog
的参数需要是格式字符串,否则可能会发生奇怪的事情.- 您应该使用快速枚举(使用
in
关键字),而不是循环遍历带有索引的容器.它不仅效率更高,而且代码更少(而且代码越少越好). - 没有理由在此处调用
performSelector:withObject:
;只需正常调用该方法即可.
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.
重写,看起来像这样:
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
}
}
同样,这些更改都不会改变您的实际问题.为了进一步提供帮助,我们需要查看更多代码.具体来说,我想看看 decompressss2z: 是什么样子.
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.
这篇关于NSOpenPanel 在 Objective-C 中获取文件名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!