【问题标题】:"Save As" in non-document based application Cocoa非基于文档的应用程序 Cocoa 中的“另存为”
【发布时间】:2011-05-19 21:23:32
【问题描述】:
我正在开发一个项目,该项目本质上是使用“sox”通过 shell 脚本创建文件。该应用程序不是基于文档的,它所做的只是调用一个创建文件的脚本,并且不会在内部保存任何数据。但是,我需要提示用户在哪里保存文件,以及在脚本运行之前使用什么文件名。让“另存为..”对话框从用户那里获取文件路径/文件名以传递给 shell 脚本的最佳方式是什么?
【问题讨论】:
标签:
cocoa
macos
unix
save-as
nssavepanel
【解决方案1】:
这很简单。你用NSSavePanel 标记了这个问题,这正是你想要使用的。
- (IBAction)showSavePanel:(id)sender
{
NSSavePanel * savePanel = [NSSavePanel savePanel];
// Restrict the file type to whatever you like
[savePanel setAllowedFileTypes:@[@"txt"]];
// Set the starting directory
[savePanel setDirectoryURL:someURL];
// Perform other setup
// Use a completion handler -- this is a block which takes one argument
// which corresponds to the button that was clicked
[savePanel beginSheetModalForWindow:someWindow completionHandler:^(NSInteger result){
if (result == NSFileHandlingPanelOKButton) {
// Close panel before handling errors
[savePanel orderOut:self];
// Do what you need to do with the selected path
}
}];
}
另请参阅文件系统编程指南中的"The Save Panel"。