How to specify range with NSPredicate in Objective C

久未见 提交于 2019-12-22 08:57:13

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/18020234/how-to-specify-range-with-nspredicate-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!