Question

Hi have a piece of jquery code which is as

var src = data.split(',');
    jQuery("#stationFrom").autocomplete({
        source: function( request, response ) {
            var matcher = new RegExp( "\\b" + jQuery.ui.autocomplete.escapeRegex( request.term ), "i" );
            response( jQuery.grep( src, function( item ){
                return matcher.test( item );
            }) );
        },

This is basically autocompleting a text field. I'm trying to emulate the same in Objective-C using NSPredicate. The query I tried is

NSArray *filteredArray = [possibleTerms filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF contains[cd] %@", inputString]];
return filteredArray;

But, this does not return the same results as the jquery autocomplete script above. How can I fix the predicate query to match the jQuery.

Is there a better way to do this?

Was it helpful?

Solution

"MATCHES" in a predicate does a regular expression match (and "[c]" is for case-insensitivity), so this should be similar to your jQuery code:

NSString *pattern = [NSString stringWithFormat:@".*\\b%@.*", [NSRegularExpression escapedPatternForString:term]];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self MATCHES[c] %@", pattern];
NSArray *filteredArray = [possibleTerms filteredArrayUsingPredicate:predicate];

If you want to get all strings in the array that start with the given term, you can use the simpler predicate

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self BEGINSWITH[c] %@", term];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top