Displaying the Completion List

When the user begins typing in a token field, the control sends (after the specified completion delay) a tokenField:completionsForSubstring:indexOfToken:indexOfSelectedItem: message to its delegate. The delegate evaluates the passed-in substring for the current token and returns an array of strings that are the possible completions of the substring.

The code in Listing 1 is in an application that makes use of the Scripting Bridge technology (introduced in OS X v10.5) to query the iTunes application for the tracks in the user’s music library. The application stores these tracks (iTunesTrack objects) in an instance variable named trackNames. The delegate in this method gets the names of all tracks and then uses the NSArray method filteredArrayUsingPredicate: to narrow this array of track names to those whose initial characters match the passed-in substring.

Listing 1  Returning a completion list

- (NSArray *)tokenField:(NSTokenField *)tokenFieldArg completionsForSubstring:(NSString *)substring indexOfToken:(NSInteger)tokenIndex indexOfSelectedItem:(NSInteger *)selectedIndex {
 
    NSArray *trackNames = [tracks valueForKey:@"name"];
    NSArray *matchingTracks = [trackNames filteredArrayUsingPredicate:
                 [NSPredicate predicateWithFormat:@"SELF beginswith[cd] %@", substring]];
    return matchingTracks;
}

The selectedIndex parameter, which is not used in this example, allows the delegate to return a default selection in the completion list.