1
votes

I have a class member "total" which is of type int. I am using "total" as an attribute in my predicate:

[NSPredicate predicateWithFormat: @"total ==%i", [searchText intValue]];

This predicate is used to collect matches when a search is executed. The predicate compares the user's search value, stored in iVar searchText , of type text with attribute "total" which is of type int.

I am able to check for equality easily like this:

 NSPredicate *filter = [NSPredicate predicateWithFormat: @"total ==%i", [searchText  intValue]];

I would now like to make the predicate more robust and work like a text search so if a user types "5" into the search box, the predicate will return 5,52,550,etc.

In other words, I would like to treat "total", which is an attribute, as a string in my predicate filter so I can use BEGINSWITH or CONTAINS.

My problem is that the attribute "total" is of type int, not a string so I am stuck.

Here is my intent (pseudo code)

NSPredicate *filter = [NSPredicate predicateWithFormat: @"[total stringValue] BEGINSWITH %@", searchText];

Or

  NSPredicate *filter = [NSPredicate predicateWithFormat: @"CAST(total, 'NSString' ) BEGINSWITH %@", searchText];

How can I do this without creating a string type in my class?

Thanks!

2

2 Answers

1
votes

[NSString stringWithFormat:@"%d"] is how you convert something from an integer into a string. You can just put it inline with your predicate declaration.

As for how to do it

without creating a string type

I'm confused as to how you would use something as a string without creating a string.

Your predicate should look like this:

NSPredicate *predicate = [NSPredicate predicateWithFormat:
                          @"(content BEGINSWITH[c] %@)", [NSString stringWithFormat:@"%d",total]];
0
votes

One (somewhat gross) way you could do this is to generate a predicate like:

total == %d OR total / 10 == %d OR total / 100 == %d OR total / 1000 == %d...

Assuming you know a small maximum value total could have.