How to validate all tokens are valid in an NSTokenField

I tried for a little while and I found that the token field calls control:isValidObject: of the NSControlTextEditingDelegate protocol when the Tab key is pressed. So you can implement a delegate method such as

- (BOOL)control:(NSControl *)control isValidObject:(id)object
{
    NSLog(@"control:%@", control);
    NSLog(@"object:%@", object);
    return NO;
}

The 'object' parameter is the content of your incomplete token. If the method returns NO, the token will not be inserted to the array of valid tokens.


I'm also struggling with this problem and found that using control:isValidObject as suggested by zonble almost gets to the solution, but that it is difficult to determine whether to return NO or YES based on the object parameter. As far as I can tell this problem is only restricted to the tab key so I implemented a pair of methods as follows;

I realise that this is horribly ugly but it's the only way I could get the NSTokenField to avoid creating tokens on tab while not impinging on other NSTextField behaviours of NSTokenField (eg moving the cursor to a new position etc).

- (BOOL)control:(NSControl *)control isValidObject:(id)object
{
    if (self.performingTab) {
        self.performingTab=NO;
        return NO;
    } else {
        return YES;
    }
}

- (BOOL)control:(NSControl *)control textView:(NSTextView *)fieldEditor
doCommandBySelector:(SEL)commandSelector 
{        
    if (commandSelector==@selector(insertTab:)) {
        self.performingTab=YES;
    }        
    return NO;        
}