raghul
raghul

Reputation: 1048

NSPredicate to compare integer using Contains

I am using a NSPredicate to search numbers in the list using UISearchBar , it works in case of strings but does not work for an integer

I am using the following predicate

predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@ contains[c]  %d", @"number", [searchBar.text intValue]]];
[objectArray filterUsingPredicate:predicate];
[tableview reloadData];

FOR example if I type 1 then all the ones in the array must be listed, I have tried == it works only for the exact number if tried any work around for this any body?

Now I get an error if I use this method "Can't use in/contains operator with collection"

Upvotes: 9

Views: 5150

Answers (2)

rdelmar
rdelmar

Reputation: 104082

I think this predicate should work for you:

predicate = [NSPredicate predicateWithFormat:@"self.number.stringValue CONTAINS %@",searchBar.text];

After thinking about this, I'm not sure why self.number.stringValue works, but it did when I tested it (self.number is an int). Not sure why I can send stringValue to an int?

Upvotes: 17

SethHB
SethHB

Reputation: 743

Predicates can be tricky to work with, so perhaps an alternative would work for you:

NSInteger index = 0;
while (index < objectArray.count)
{
    NSString *currentString = [objectArray objectAtIndex:index];
    if ([currentString rangeOfString:searchBar.text].length == 0)
    {
        [objectArray removeObjectAtIndex:index];
        continue;
    }
    index++;
} 

Here, any strings in your array that do not contain your searchBar text will be removed.

Upvotes: -1

Related Questions