NSOpenPanel - Choosing any file and ignoring packages

Q: How do I setup NSOpenPanel to exclude file packages?

A: You need to implement the delegate method:

- (BOOL)panel:(id)sender shouldShowFilename:(NSString*)filename

In this method you must filter out file system objects that are packaged directories.

The Finder and NSOpenPanel treat packaged directories differently than other directories. Instead of displaying the contents of the packaged directory, they treat it as if it were a single file. Packaged directories usually have the extension: .app, .bundle, .framework, .plugin, .kext. If your application wishes to deal with only files, excluding these types of packages, you need to alter the behavior of NSOpenPanel.

IMPORTANT: This solution is for applications that want to show any file. If your application knows a specific set of file types it can choose, then all you need to do is setup an NSArray of types and pass it in when running NSOpenPanel. Example: -(int)runModalForTypes:(NSArray*)fileTypes

As you setup up your NSOpenPanel, make sure you become its delegate by calling:

[openPanel setDelegate: self];

Proceed to implement the following delegate method to only allow choosing files and not packages.

Listing 1: The delegate method to filter out packaged files.


- (BOOL)panel:(id)sender shouldShowFilename:(NSString*)filename
{
    BOOL showObject = YES;

    NSDictionary* fileAttribs = [[NSFileManager defaultManager]
                                    fileAttributesAtPath:filename traverseLink:YES];
    if (fileAttribs)
    {
        // check for packages
        if ([NSFileTypeDirectory isEqualTo:[fileAttribs objectForKey:NSFileType]])
        {
            if ([[NSWorkspace sharedWorkspace] isFilePackageAtPath:filename] == NO)
                showObject = YES;    // it's a folder, OK to show
            else
                showObject = NO;    // it's a packaged directory, don't show
        }
        else
        {
            showObject = YES;  // it's a file, OK to show
        }
    }

    return showObject;
}

Document Revision History

DateNotes
2007-01-25First Version

Posted: 2007-01-25


Did this document help you?
Yes: Tell us what works for you.
It’s good, but: Report typos, inaccuracies, and so forth.
It wasn’t helpful: Tell us what would have helped.