Search code examples
objective-ccocoamacostagsnstokenfield

Populate an NSTokenField with tokens from a container of objects


I have an NSTableView and an NSTokenField in a window. I have implemented the following delegate methods:

tokenField:completionsForSubstring:indexOfToken:indexOfSelectedItem:
tokenField:representedObjectForEditingString:
tokenField:displayStringForRepresentedObject:

I want to make it so that when a row is selected in it, the NSTokenField gets populated with the tags that are contained in an NSMutableSet of the row object. How do I populate an NSTokenField with tokens if I have a container of the objects that they represent (and therefore the strings that need to be made into tokens)?


Solution

  • I figured it out. In the code below ms is an NSMutableSet that contains my objects.

            //set the token field
            NSMutableArray *ma = [[NSMutableArray alloc] init];
            for (MyClass *anObject in ms){
                [ma addObject:anObject];
            }
    
            //sort the array
            NSSortDescriptor *sorter = [[NSSortDescriptor alloc] initWithKey: @"title" ascending: YES];
            NSArray *sortDescriptorArray = [[NSArray alloc] initWithObjects:sorter, nil];
    
            [ma sortUsingDescriptors:sortDescriptorArray];
            [tokenField setObjectValue:ma];
    

    The key is the last line: [tokenField setObjectValue:ma];