CoreData conditionally fetching on NSDate using NSPredicate (swift)

前端 未结 2 890
臣服心动
臣服心动 2021-01-06 17:54

Basically I have an entity called TimeLoc that has three attributes: time, latitude and longitude. And their types are Date, Double and Double respectively. I got stuck when

相关标签:
2条回答
  • 2021-01-06 18:17

    I guess you are sending parameters to the predicate in NSDate format :

    let predicate = NSPredicate(format: "time>= \(startTime) AND time<= \(endTime)")
    

    Here your startTime and endTime is of type NSDate . Try to convert it in String format and pass it to the predicate . It should work .

    Reference : NSPredicate: filtering objects by day of NSDate property

    0 讨论(0)
  • 2021-01-06 18:21

    The accepted solution did not work for me, though it made intuitive sense. As an alternative, I created a predicate so search a range, like so:

    "%K BETWEEN {%@, %@}" where %K is my key path, and the two %@s are my start and end dates.

    let datePredicate = NSPredicate(format: "%K BETWEEN {%@, %@}", argumentArray: [#keyPath(Activity.startTime), startDate!.startOfDay, endDate!.endOfDay])
    
    0 讨论(0)
提交回复
热议问题