如何在Objective C中使用NSPredicate指定范围 [英] How to specify range with NSPredicate in Objective C
问题描述
我想通过指定范围来查询 sqllite 表.所以这就像给我 id 列在 3000 和 3010 之间的所有记录.
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.
我尝试了 Apple 推荐的方法,但没有奏效.这是我尝试过但失败的方法.
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]];
我有 2 个字符串,称为 start 和 end.我更新了 Apple 的示例如下.
I have 2 strings called start and end. I updated Apple's example as following.
NSPredicate *betweenPredicate =
[NSPredicate predicateWithFormat: @"%@ BETWEEN %@", columnName, @[start,end]];
当我使用上述谓词 executeFetchRequest 时,即使表中有与谓词匹配的记录,我也会得到 0 条记录.有人可以指出我哪里出错了吗?
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?
推荐答案
您必须使用 %K
格式说明符作为属性名称:
You have to use the %K
format specifier for attribute names:
[NSPredicate predicateWithFormat: @"%K BETWEEN %@", columnName, @[start,end]];
如果这不起作用(我从未对核心数据获取请求使用BETWEEN"),您可以用等价的谓词替换它
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];
这篇关于如何在Objective C中使用NSPredicate指定范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!