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: , , ,
Posted in Programming | 1 Comment »