Friday, February 9, 2007

NSSavePanel in Objective-C

Here is the code to use a basic NSOpenPanel.

1. NSSavePanel *save = [NSSavePanel savePanel];
2.
3. //Optional : Add Code here to change NSSavePanel basic configuration
4.
5. int result = [save runModal];
6.
7. if (result == NSOKButton){
8. NSString *selectedFile = [save filename];
9. //Add Additional code to handle the save;
10. }

Code Explained:
Line 1: When you declare a NSSavePanel, you need to make sure you put a *. Now to retrieve a basic save panel, you just need to use [NSSavePanel savePanel] and place it to the right of the =.

Line 3: You would replace this comment with additional configuration code. These are properties within the panel class like setRequiredFileType:NSString or setCanCreateDirectories:BOOL.

Line 5: When you are ready to present the panel, you will create a integer (int) called anything really, I am just using results since that is what it is storing. When the runModal method is called for the panel, it will return a int based on what the user did in the panel. Typically the user will press the OK Button or the Cancel Button.

Line 7: This is the check to see if the user clicked OK. NSOKButton is an enumeration (enum) that contains the int representation of a Dialog Result equal to OK. If the result is equal to this, then the user pressed okay and you can proceed with your code to handle the save. Now notice the = and the ==. They are used differently! The = means your are setting a value. The == means your are comparing values.

3 comments:

faceleg said...

Thanks, this was extremely helpful.

As I'm just starting out with Cocoa, the Apple docs are Greek to me.

It was great to find such a helpful article!

Unknown said...

Thanks :-)

Daniel J Roth said...

Thanks so much! This made this process so much more painless.