Getting and Setting Token-Field Values

To retrieve the objects represented by the tokens in a token field, send the token field an objectValue message. Although this method is declared by NSControl, NSTokenField implements it to return an array of represented objects. If the token field simply contains a series of strings, objectValue returns an array of strings. To set the represented objects of a token field, use the setObjectValue: method, passing in an array of represented objects. If these objects aren’t strings, NSTokenField then queries its delegate for the display strings to use for each token.

A common place to call objectValue is in an action method. Listing 1 gives an example of such a method.

Listing 1  Getting and setting the contents of a token filed

- (IBAction)addToPlaylist:(id)sender { // sender is token field
    // add songs to playlist, select first one added
    NSIndexSet *curSongIndex = [NSIndexSet indexSetWithIndex:(NSUInteger)[currentList count]];
    [currentList addObjectsFromArray:[sender objectValue]];
    [songTable reloadData];
    [songTable selectRowIndexes:curSongIndex byExtendingSelection:NO];
    [sender setObjectValue:nil];

Note that this method clears the token field by setting its object value to nil.