Search code examples
objective-ccocoaautocompleteparsingnstokenfield

NSTokenField autocomplete


I'm creating an application which uses an NSTokenField. I need autocompletion. I'm using an NSURLRequest to request data from http://stackoverflow.com/filter/tags?_=<timestamp>&limit=6&q=<str_to_autocomplete>&timestamp=<timestamp>

Where <timestamp> is the current timestamp, an <str_to_autocomplete> is the string to autocomplete. So, e.g. http://stackoverflow.com/filter/tags?_=1263657227137&q=lol&limit=6&timestamp=1263657227137

The response is in this format:

javascript|23179
jquery|16936
sql-server|11768
ruby-on-rails|8669
best-practices|7037
ruby|6722

(The number is the number of times this tag is used).

I need to give provide the user a list under the NSTokenField with this list of tags, and the user can either select one of the list, or continue typing.

Can anyone help me? Thanks.

Edit: I'm looking at Mac Dev Center now. Should I use this method: tokenField:completionsForSubstring:indexOfToken:indexOfSelectedItem: ?


Solution

  • This will be send to the delegate to query an array of strings:

    tokenField:completionsForSubstring:indexOfToken:indexOfSelectedItem: 
    

    These strings should then be processed by the tokenField in representedObject (or not if you need only strings).

    Example in your tokenField delegate:

    - (NSArray *)tokenField:(NSTokenField *)tokenField completionsForSubstring:(NSString *)substring indexOfToken:(NSInteger)tokenIndex indexOfSelectedItem:(NSInteger *)selectedIndex
    {
        //code to find the tags strings corresponding to substring (the string typed in the token)
        //then put them in an array (returnArray)
        return returnArray;
    }
    

    The tokenField will present the strings completed in a menu as you type. All details are in the doc.