How to add a file selector/opener in cocoa with Interface Builder?

Interface Builder is for designing and linking together the interface. You want to open files and put them in an array, which is safely on the Xcode side of things. Have the button's action show an NSOpenPanel and give the results to your table's data source.


I found this page when looking up, how to open up a file open box in Cocoa. With the release of OS X 10.7 a lot of the samples that is linked to is now deprecated. So, here is some sample code that will save you some compiler warnings:

// -----------------
// NSOpenPanel: Displaying a File Open Dialog in OS X 10.7
// -----------------

// Any ole method
- (void)someMethod {
  // Create a File Open Dialog class.
  NSOpenPanel *openDlg = [NSOpenPanel openPanel];

  // Set array of file types 
  NSArray<NSString*> *fileTypesArray = @[@"jpg", @"gif", @"png"];

  // Enable options in the dialog.
  [openDlg setCanChooseFiles:YES];    
  [openDlg setAllowedFileTypes:fileTypesArray];
  [openDlg setAllowsMultipleSelection:YES];

  // Display the dialog box.  If OK is pressed, process the files.
  if ([openDlg runModal] == NSModalResponseOK) {
    // Get list of all files selected
    NSArray<NSURL*> *files = [openDlg URLs];

    // Loop through the files and process them.
    for (NSURL *file in files) {
      // Do something with the filename.
      NSLog(@"File path: %@", [file path]);
    }
  }
}

This must be done in Xcode. The code here should work fine.

Just hook the button up with a method using IB and use that example as a guide of what to put in the method.

There's also all sorts of good help WRT NSOpenPanel at Cocoadev, including tips on opening the panel as a sheet instead of a modal window.

Of course you should always read the Apple documentation as well.