Cocoa Bindings and NSPopUpButton

Posted July 29th, 2008 by Chris

A frustrating problem I came across today when I tried binding an NSPopUpButton’s selection key to an NSArrayController’s selection was that the NSPopUpButton would always display a ‘ghost’ object -one of the opaque classes internal to Cocoa/Core-Data Bindings(<_NSControllerObjectProxy… or similar).

It turns out that NSPopUpButton does not record the user’s selection, so even if I had been able to get rid of the ghost object, I wouldn’t have been able to access the selected object.

The solution is to manually maintain a currently selected object in the window controller - File’s Owner in Interface Builder; in this case, selectedPackage:

In MyWindowController.m:


- (void)setSelectedPackage:(NSManagedObject *)package
{
// ... checks ...
selectedPackage = package;
}
 
- (NSManagedObject *)selectedPackage
{
return selectedPackage;
}

In Interface Builder, the NSPopUpButton should be bound to the NSArrayController (Packages) and the File’s Owner as:

Content: Packages.arrangedObjects
Content Values: Packages.arrangedObjects;modelPath=packageName
Selection: File’s Owner.selectedPackage

A default selection can then be provided by calling the setSelectedPackage: method.

Tags: , , ,

This entry was posted on Tuesday, July 29th, 2008 at 10:37 pm and is filed under Programming. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

One Response to “Cocoa Bindings and NSPopUpButton”

  1. Tom says:

    Chris
    Thanks for the info. After struggling with this same issue a while back, I also learned the he controller’s selection is not recorded but the selectedindex is. You can alternately bind to the NSArrayController’s selectedindex and manipulate the result from there. This will also eliminate the gost object. eg. int si; Bind Controller’s selectedindex to si. [[NSArrayController arrangedObjects]objectAtIndex:si]; This is one area that apple’s Docs do not do a good job of explaining. Thanks again

Post a Comment