Querying Button Matrices

A group of radio buttons or checkboxes is programmatically an NSMatrix object whose constituent objects are NSButtonCell objects. Matrix objects are a special kind of control. Each of its cells can have its own target object and action selector specified. Additionally, an NSMatrix may have its own target and action selector. (For more on target-action in relation to matrix objects, see Matrix Programming Guide.)

To find out which radio button or checkbox a user selected—at the moment he or she clicks it—you could specify a target and a different action selector for each cell in the matrix, and then implement the corresponding action method. However, a more efficient way to query the current selection in matrices of radio buttons or checkboxes is to implement target-action for the NSMatrix object itself, and in the action method determine which cell (or cells) are now selected. The NSMatrix methods for this are selectedCell and selectedCells.

Listing 1 shows an implementation of an action method that responds to a selection in a matrix of radio buttons.

Listing 1  Querying a matrix object for the selected radio-button cell

- (IBAction)findSelectedButton:(id)sender { // sender is NSMatrix object
    NSButtonCell *selCell = [sender selectedCell];
    NSLog(@"Selected cell is %d", [selCell tag]);

This code snippet illustrates another technique you can apply when handling selection of cells in matrices. You can assign numeric tags to each cell in a matrix to identify it, and then query for those tag values when handling selections.