16

NSSavePanel used to have a runModalForDirectory:file: method which let you preset the directory and filename for a save panel. But that is deprecated in 10.6

When creating an NSSavePanel, how can I preset the filename without using the deprecated method?

Michael Johnston
  • 5,298
  • 1
  • 29
  • 37

2 Answers2

37

Use the setNameFieldStringValue: method, which was added in 10.6, before running the save panel. If you want to set the default directory too, you will need the setDirectoryURL: method, also added in 10.6.

NSString *defaultDirectoryPath, *defaultName;
NSSavePanel *savePanel;
...
[savePanel setNameFieldStringValue:defaultName];
[savePanel setDirectoryURL:[NSURL fileURLWithPath:defaultDirectoryPath]];
[savePanel runModal];
ughoavgfhw
  • 39,734
  • 6
  • 101
  • 123
7

There is a method that I didn't notice at first, NSSavePanel#setNameFieldStringValue, which sets the filename.

here is a complete example in macruby syntax:

def run_save_settings_dialog(sender)
  dialog = NSSavePanel.savePanel
  dialog.title = "Save Settings"
  dialog.canCreateDirectories = true
  dialog.showsHiddenFiles = true
  dialog.nameFieldStringValue = "MyFile"
  dialog.canChooseFiles = true
  dialog.canChooseDirectories = false
  dialog.allowsMultipleSelection = false
  dialog.setDirectoryURL NSURL.fileURLWithPath("some/path")
  if dialog.runModal == NSFileHandlingPanelOKButton
    save_settings(dialog.URL)
  end
end

def save_settings(file_url)
  File.open(file_url.path, 'w') {|f| f.write "Stuff" }
end
Michael Johnston
  • 5,298
  • 1
  • 29
  • 37