neo
neo

Reputation: 2042

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?

Upvotes: 4

Views: 3063

Answers (1)

Martin R
Martin R

Reputation: 539745

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];

Upvotes: 9

Related Questions