You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用NSPredicate筛选Core Data中keyPath为nil或小于指定日期的数据

解决Core Data NSPredicate组合OR条件无效的问题

你的问题出在组合谓词时参数数量不匹配:格式字符串里有两个%K占位符,但你只传入了一次#keyPath(RepeatingTask.endDate)参数,导致谓词解析错误,无法正确执行查询。

正确写法有两种:

1. 重复传入keyPath参数

直接为两个%K分别提供对应参数:

let endDatePredicate = NSPredicate(format: "%K > %@ || %K == nil", #keyPath(RepeatingTask.endDate), date as NSDate, #keyPath(RepeatingTask.endDate))

2. 使用参数索引复用keyPath

通过%1$K复用第一个参数,避免重复写keyPath:

let endDatePredicate = NSPredicate(format: "%1$K > %@ || %1$K == nil", #keyPath(RepeatingTask.endDate), date as NSDate)

额外提醒:

你描述的需求是“获取对应keyPath值为nil,或者小于指定日期的数据”,但原代码里用的是>(大于),如果是笔误,记得把运算符改成<:

let endDatePredicate = NSPredicate(format: "%1$K < %@ || %1$K == nil", #keyPath(RepeatingTask.endDate), date as NSDate)

内容的提问来源于stack exchange,提问作者user16783054

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 07:36:20