gpt4 book ai didi

swift - 带有日期范围的 Core Data 复合提取的意外结果

转载 作者:行者123 更新时间:2023-12-04 09:15:01 25 4
gpt4 key购买 nike

我有一个简单的数据模型,其中访问者(fName 和 lName)和访问(日期、评论)处于 1 米关系。我正在尝试获取特定日期的所有访问者。为了实现这一点,我需要创建一个谓词来查找在当天开始到结束之间进行访问的所有实体。我试过了:

...
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "visitor")
let filter = "ANY visits.date >= %@ AND ANY visits.date < %@" // visits is the visitors relation to visits
let startTime = calendar.startOfDay(for: thisDay) as NSDate
let endTime = calendar.date(bySettingHour: 23, minute: 59, second: 59, of: thisDay)! as NSDate
fetchRequest.predicate = NSPredicate(format: filter, startTime, endTime)
结果是访问日期在这一天及之后的所有访问者。因此复合谓词的第二部分无效!
我也尝试将这两个条件与 NSCompoundPredicate 结合起来,但结果是一样的。我已经用相同的复合谓词试验了日期类型以外的其他类型,并且这些都运行良好。因此,尽管在 Internet 上进行了大量搜索,但我不知道如何使用谓词解决这个简单的查询。
任何建议都是最受欢迎的!

最佳答案

您的谓词通过 visits.date >= startDate 获取与(至少一个)访问相关的所有访问者并(至少)访问 visits.date < endDate .问题是这两个相关对象不需要相同才能使谓词返回 true .
您需要的是一个“子查询”:来自(相关) NSExpression documentation :

This method creates a sub-expression, evaluation of which returns asubset of a collection of objects. It allows you to createsophisticated queries across relationships, such as a search formultiple correlated values on the destination object of arelationship.

...

The string format for a subquery expression is:

SUBQUERY(collection_expression, variable_expression, predicate);

where expression is a predicate expression that evaluates to acollection, variableExpression is an expression which will be used tocontain each individual element of collection, and predicate is thepredicate used to determine whether the element belongs in the resultcollection.


在您的情况下,它应该是(未经测试):
NSPredicate(format: "SUBQUERY(visits, $v, $v.date >= %@ and $v.date < $@).@count > 0",
startTime, endTime)
这将获取与至少一次访问相关的所有访问者,这些访问者的日期在指定范围内。

关于swift - 带有日期范围的 Core Data 复合提取的意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63270329/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com