Question

I need to keep an NSPathControl updated with the currently selected path in an NSBrowser, but I'm having trouble figuring out a way of getting notifications when the path has changed from the NSBrowser. The ideal way to do this would just to be to observe the path key path in the NSBrowser, but that gives a KVO can only observe set<key> methods which return void message and no updates (setPath returns a bool success value).

I also tried observing the selectedCell key path, but I'm not getting notifications when the selection there is changed.

Is there some other really obvious way to do this that I'm missing?

Was it helpful?

Solution

Courtesy of Rob Keniger over at Cocoa Dev:

Have you looked at the SimpleBrowser example in /Developer/Examples? It shows how to get the current selection when it is changed by the user, basically by just setting up the action of the NSBrowser.

That is indeed the way to do it. Just implement a - (void)broswerClicked: method (including mapping it in interface builder) with whatever you want to happen each time the selection changes inside that method, e.g.

- (void)browserClicked:(id)browser {
    self.pathToSelectedCell = [browser path]; // NSPathControl is bound to pathToSelectedCell
}

OTHER TIPS

I just checked in IB, and it looks like NSBrowser has a selection index paths binding (an array of NSIndexPath objects) that you could possibly monitor with KVO. It's strange but I don't see any mention of it in the docs, so you might need to do a little research to see if that's something you should or shouldn't use, even if it seems to work. If it does, in your KVO observation method you would find the browser's current path, and convert that to an NSURL the path control can use.

If that doesn't work there's also the delegate methods - (BOOL)browser:(NSBrowser *)sender selectRow:(NSInteger)row inColumn:(NSInteger)column and - (BOOL)browser:(NSBrowser *)sender selectCellWithString:(NSString *)title inColumn:(NSInteger)column.

As of 10.6, one can find out which items are selected, by using the delegate callback as follows:

- (NSIndexSet *)browser:(NSBrowser *)browser selectionIndexesForProposedSelection:(NSIndexSet *)proposedSelectionIndexes inColumn:(NSInteger)column
{
    NSLog(@"New first item of the new selection is at index %@", [proposedSelectionIndexes firstIndex]);
    // Do something with the selected index or indicies
    return proposedSelectionIndexes; // Allow the selection to occur by not changing this
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top