How to specify a range with NSPredicate in Objective-C

I want to query the sqllite table by specifying a range. So I like giving me all the records with an identity column between 3000 and 3010.

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

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

I have two lines starting and ending. I updated the Apple example as follows.

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

When I execute a FetchRequest with the above predicate, I get 0 records, even if there are records in the table matching the predicate. Can someone point out where I am wrong?

+4
source share
1 answer

You must use the %K format specifier for attribute names:

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

If this does not work (I never used "BETWEEN" for Core Data fetch queries), you can replace it with an equivalent predicate

 [NSPredicate predicateWithFormat: @"%K >= %@ AND %K <= %@", columnName, start, columnName, end]; 
+8
source

Source: https://habr.com/ru/post/1494980/


All Articles