Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify range with NSPredicate in Objective C

I want to query sqllite table by specifying a range. So it's like give me all records whose id column between 3000 and 3010.

I tried what Apple recommends, but it didn't work. Here is what I tried and failed.

NSPredicate *betweenPredicate =
[NSPredicate predicateWithFormat: @"attributeName BETWEEN %@", @[@1, @10]];

I have 2 strings called start and end. I updated Apple's example as following.

NSPredicate *betweenPredicate =
[NSPredicate predicateWithFormat: @"%@ BETWEEN %@", columnName, @[start,end]];

When I executeFetchRequest with the above predicate I get 0 records even though the table has records matching the predicate. Can someone point where I go wrong?

like image 823
neo Avatar asked Jan 13 '23 18:01

neo


1 Answers

You have to use the %K format specifier for attribute names:

[NSPredicate predicateWithFormat: @"%K BETWEEN %@", columnName, @[start,end]];

If that does not work (I have never used "BETWEEN" for Core Data fetch requests), you could replace it by the equivalent predicate

[NSPredicate predicateWithFormat: @"%K >= %@ AND %K <= %@",
         columnName, start, columnName, end];
like image 101
Martin R Avatar answered Jan 22 '23 18:01

Martin R