如何使用目标C获取文件路径 [英] How to acquire a file path using objective c
问题描述
我想要一个仅返回finder中所选文件的完整文件路径的函数.
I want a function which just returns the full file path of a file selected in finder.
我目前具有此功能:
+ (NSString*)choosePathWindow:(NSString*)title buttonTitle:(NSString*)buttonTitle allowDir:(BOOL)dir allowFile:(BOOL)file{
[NSApp activateIgnoringOtherApps:YES];
NSOpenPanel *openPanel = [NSOpenPanel openPanel];
[openPanel setLevel:NSFloatingWindowLevel];
[openPanel setAllowsMultipleSelection:NO];
[openPanel setCanChooseDirectories:dir];
[openPanel setCanCreateDirectories:dir];
[openPanel setCanChooseFiles:file];
[openPanel setMessage:title];
[openPanel setPrompt:buttonTitle];
NSString* fileName = nil;
if ([openPanel runModal] == NSModalResponseOK)
{
for( NSURL* URL in [openPanel URLs])
{
fileName = [URL path];
}
}
[openPanel close];
return fileName;
}
但是,这通常表现得很糟糕,并且结结巴巴地出现,并且在选择文件(我有i7-7700k和16GB ddr4)后经常挂起,并且在单击取消"时始终挂起.我也相信,这可能与我拥有的外部网络安装有关.但是其他任何软件,例如PHPStorm或Chrome,都可以在同一窗口中正常工作.
But this usually behaves awfully and stutters into view and often hangs after choosing a file (I have an i7-7700k and 16GB ddr4) and always hangs when clicking cancel. I also believe that this may be to do with external network mounts I have. But any other software such as PHPStorm or Chrome work fine with the same window.
有更好的方法吗?
推荐答案
代码看起来不错.尝试从主线程调用函数;模式对话框需要此功能,通常不会自己执行.无论如何,Powebox(在沙箱中运行NSOpenPanel的东西)有点像野兽.另外,直接从Xcode启动的调试版本(不太好)和从Finder启动的发布版本可能会得到不同的结果.
The code looks fine. Try calling your function from main thread; modal dialogs need this and usually don't enforce it themselves. In any case the Powebox (the thing that runs NSOpenPanel in sandbox) is a bit of a beast. Also you might get different results with debug build launched directly from Xcode (not so good) and release build launched from Finder.
要测试NSOpenPanel,请执行以下操作:尝试以访客帐户运行您的App,以消除所有杂乱无章的东西.
To test NSOpenPanel: Try running your App under a guest account to eliminate all stuff that's cluttering the sandbox .
这篇关于如何使用目标C获取文件路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!