Thursday, February 8, 2007

NSOpenPanel in Objective-C

Here is the code to use a basic NSOpenPanel.

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

Code Explained:
Line 1: When you declare a NSOpenPanel, you need to make sure you put a *. Now to retrieve a basic open panel, you just need to use [NSOpenPanel openPanel] 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 setCanChooseDirectories:BOOL or setAllowedFileTypes:NSArray

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 open. Now notice the = and the ==. They are used differently! The = means your are setting a value. The == means your are comparing values.

1 comment:

Chinmoy said...

Useful blog. I made a similar blog, but I actually post more on other topics than Cocoa programming. If you are interested, check out http://gavmacprogramming.wordpress.com