How to create a Save As dialogue with NSSavePanel

- by

Likewise we can save our previously selected file using an NSSavePanel. It too is easy to use, just as the NSOpenPanel.

For a save action to make sense we need to have some data to save, so in this example we will copy an existing file (self.myURL) to the new URL that the save panel returns. We’ll let the NSFileManager just create a copy with a new name that the user specifies using the save panel:

- (IBAction)saveFile:(id)sender {
    
    // create the save panel
    NSSavePanel *panel = [NSSavePanel savePanel];
    
    // set a new file name
    [panel setNameFieldStringValue:@"NewFile.png"];
    
    // display the panel
    [panel beginWithCompletionHandler:^(NSInteger result) {
        
        if (result == NSFileHandlingPanelOKButton) {
            
            // create a file namaner and grab the save panel's returned URL
            NSFileManager *manager = [NSFileManager defaultManager];
            NSURL *saveURL = [panel URL];
            
            // then copy a previous file to the new location
            [manager copyItemAtURL:self.myURL toURL:saveURL error:nil];
        }
    }];
    
}

The only alien looking thing here is the use of a Block (like it is in the NSOpenPanel). This is the equivalent to an anonymous function in JavaScript, basically a block of code that runs upon completion. As it’s part of the method call, the closing ] is way at the bottom.

Further Reading

Apple’s NSSavePanel Class Reference:

A Short Practical Guide to Blocks:



If you enjoy my content, please consider supporting me on Ko-fi. In return you can browse this whole site without any pesky ads! More details here.

Leave a Comment!

This site uses Akismet to reduce spam. Learn how your comment data is processed.