如何在Objective C中使用NSPredicate指定范围

时间:2013-08-02 15:05:10

标签: ios objective-c sqlite nspredicate

我想通过指定范围来查询sqllite表。所以它就像给我所有记录,其id列在3000和3010之间。

我尝试了Apple推荐的产品,但它没有用。这是我尝试过的失败。

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

我有两个名为start和end的字符串。我将Apple的示例更新为以下内容。

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

当我使用上述谓词执行executeRequest时,即使该表具有与谓词匹配的记录,我也会得到0条记录。有人能说出错的地方吗?

1 个答案:

答案 0 :(得分:8)

您必须使用%K格式说明符来表示属性名称:

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

如果这不起作用(我从未使用“BETWEEN”进行核心数据获取请求),那么 可以用等效谓词替换它

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