< Previous PageNext Page > Hide TOC

Getting the Current Selection

You can get the currently selected item in the browser of an NSSavePanel or NSOpenPanel object by having the delegate of the panel object implement the panelSelectionDidChange: delegation method. The delegate then can perform some operation based on the user’s selection, such as displaying metadata about a chosen file in an accessory view, as illustrated in Figure 1.


Figure 1  Displaying information about the current selection

Displaying information about the current selection

In its implementation of panelSelectionDidChange:, the delegate sends a message back to the NSOpenPanel or NSSavePanel object (sender) to get the current filename. For NSSavePanel, this message is filename; for NSOpenPanel, send filenames and then get the first item in the array. Listing 1 shows how you might implement the method to display in the information in the accessory view in Figure 1.

Listing 1  Getting the selection in the panel browser

- (void)panelSelectionDidChange:(id)sender {
    NSArray *curFiles = [sender filenames];
    if ([curFiles count] == 1) { // ignore multiple selections
        NSString *curPath = [curFiles objectAtIndex:0];
        if (curPath != nil) {
            NSDictionary *fAttrs = [[NSFileManager defaultManager] fileAttributesAtPath:curPath traverseLink:YES];
            if (fAttrs != nil) {
                [infoFile setStringValue: [curPath lastPathComponent]];
                [infoMod setStringValue: [[fAttrs objectForKey:NSFileModificationDate] descriptionWithCalendarFormat:@"%a, %b %d, %Y %H:%M:%S" timeZone:nil locale:nil]];
                [infoOwner setStringValue: [fAttrs objectForKey: NSFileOwnerAccountName]];
                [infoGroup setStringValue: [fAttrs objectForKey: NSFileGroupOwnerAccountName]];
            }
        }
    }
}

In this code example, the delegate uses the NSFileManager method fileAttributesAtPath:traverseLink: to fetch information about the currently selected file. It then sets the string value of various text fields in the accessory view.



< Previous PageNext Page > Hide TOC


© 2006 Apple Computer, Inc. All Rights Reserved. (Last updated: 2006-11-07)


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.