Typically, you access an NSOpenPanel by invoking the openPanel
method. When the class receives an openPanel
message, it tries to reuse an existing panel rather than create a new one. If a panel is reused, its attributes are reset to the default values so that the effect is the same as receiving a new panel. Because Open panels may be reused, you shouldn’t modify the instance returned by openPanel
except through the methods listed below (and those inherited from NSSavePanel). For example, you can set the panel’s title and whether it allows multiple selection, but not the arrangement of the buttons within the panel. If you must modify the Open panel substantially, create and manage your own instance using the constructors or the alloc...
and init...
methods rather than the openPanel
method.
The following Objective-C code example shows the NSOpenPanel displaying only files with extensions of “.td” and allowing multiple selection. If the user makes a selection and clicks the OK button (that is, runModalInDirectoryrunModalForDirectory:file:types:
returns NSOKButton
), this method opens each selected file:
- (void)openDoc:(id)sender |
{ |
int result; |
NSArray *fileTypes = [NSArray arrayWithObject:@"td"]; |
NSOpenPanel *oPanel = [NSOpenPanel openPanel]; |
[oPanel setAllowsMultipleSelection:YES]; |
result = [oPanel runModalForDirectory:NSHomeDirectory() |
file:nil types:fileTypes]; |
if (result == NSOKButton) { |
NSArray *filesToOpen = [oPanel filenames]; |
int i, count = [filesToOpen count]; |
for (i=0; i<count; i++) { |
NSString *aFile = [filesToOpen objectAtIndex:i]; |
id currentDoc = [[ToDoDoc alloc] initWithFile:aFile]; |
} |
} |
} |
NSOpenPanel can accept file types specified as either filename extensions or encoded HFS file types. To encode an HFS file type into an acceptable NSString use the function NSFileTypeForHFSTypeCode
. (See “HFS File Types” for details.) When specifying file types for NSOpenPanel, you should include any allowed HFS file types as well as the filename extensions. For example, if you want to open text files, specify a file types array like this:
NSArray *fileTypes = [NSArray arrayWithObjects: @"txt", @"text", |
NSFileTypeForHFSTypeCode( 'TEXT' ), nil]; |
© 2006 Apple Computer, Inc. All Rights Reserved. (Last updated: 2006-11-07)