Providing Data for a Combo Box

The NSComboBox control can be set up to populate the pop-up list either from an internal item list or from an object that you provide, called its data source. Specify which to use with setUsesDataSource:. By default, a combo box uses the internal list.

If you specify that a combo box uses an external data source and then try to invoke a method that uses the internal list—such as addItemWithObjectValue:—the method throws an exception.

Working With an External Data Source

An external data source declares the methods that the combo box uses to access its data. Use one if an internal list isn’t efficient for your data. An external data source can store its items in any way, but it must be able to identify them by an integer index.

To specify that combo box uses an external data source, first use setUsesDataSource: with YES as the argument, then use setDataSource: with your data source object as the argument. If you use setDataSource: before setUsesDataSource:, setDataSource: throws an exception.

The data source must define these methods. The method setDataSource: logs a warning if its argument doesn’t implement them.

The data source can optionally define these methods. The method setDataSource doesn’t check for them and the combo box invokes them only if they’re available.

And here are some NSComboBox methods your data source may need if it loads data in the background:

The combo box treats objects provided by its data source as values to be displayed in the combo box’s pop-up list. If these objects aren’t of common value classes—such as strings, numbers, and so on—you’ll need to create a custom NSFormatter to display them. See Data Formatting Guide for more information.

Working with an Internal List

NSComboBox provides a complete set of methods that allow you to add, insert, and delete items in the internal item list for combo boxes that don’t use a data source:

If usesDataSource returns YES and you use any of the above methods, the method will throw an exception. By default, usesDataSource returns NO.