29 July 2008 · About 1 minute read

Cocoa: Cocoa Bindings and NSPopUpButton

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:

```objc- (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.

Chris Blunt
Chris Blunt@cblunt
Chris is the founder of Plymouth Software. As well as code and business, he enjoys being a Dad, swimming, and the fine art of drinking tea.