Returning Represented Objects

When the user enters a string and presses a tokenizing character, the token field sends the tokenField:representedObjectForEditingString: message to its delegate. This message asks the delegate to return a represented object for the entered token string (the editingString parameter in Listing 1). In this example, the delegate finds and returns the iTunesTrack object with the name matching editingString.

Listing 1  Returning represented objects for tokens

- (id)tokenField:(NSTokenField *)tokenField representedObjectForEditingString: (NSString *)editingString {
    iTunesTrack *track = [tracks objectWithName:editingString];
    if ([track exists])
        return track;
    return nil;
}

If the delegate returns nil, no represented objects are associated with the token string. Otherwise, the token field queries its delegate for the display string to use for each token by invoking the tokenField:displayStringForRepresentedObject: method. Listing 2 shows an implementation of this delegation method.

Listing 2  Returning the display string for a represented object

- (NSString *)tokenField:(NSTokenField *)tokenFieldArg displayStringForRepresentedObject:(id)representedObject {     return [representedObject name]; }