首页 > 解决方案 > 如何正确构建 NSPredicate 以从具有特定日期标签的 CoreData 对象创建值数组?

问题描述

我试图从特定日期输入的 CoreData 对象中获取值。我在 SO 和其他网站上发现了一些有点类似的问题,并且已经广泛使用并拼凑了看起来应该可以工作的代码,但它没有返回任何我知道的数据值。我是一个相对初学者,所以基本的反应是值得赞赏的。代码如下。抱歉,如果这是矫枉过正,但我​​不确定故障在哪里。提前致谢。

 @IBAction func plusDayToEdit(_ sender: Any) {
    if dayToEdit < 30 {
        dayToEdit += 1
        dayToEditLabel.text = String(dayToEdit)
        previousDayFetchRequest()
    } else {

    }

func previousDayFetchRequest() {

guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }

let managedContext = appDelegate.persistentContainer.viewContext

let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Entry")

var calendar = Calendar.current
calendar.timeZone = NSTimeZone.local

let dateToEdit = calendar.date(byAdding: .day, value: (0 - dayToEdit), to: Date())
let startDate = calendar.startOfDay(for: dateToEdit!)
let endDate = calendar.date(byAdding: .day, value: 1, to: startDate)

let fromPredicate = NSPredicate(format: "entryDate <= %@", startDate as NSDate)
let toPredicate = NSPredicate(format: "entryDate > %@", endDate! as NSDate)
let dateToEditPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [fromPredicate, toPredicate])

fetchRequest.predicate = dateToEditPredicate 

标签: swiftcore-datanspredicate

解决方案


推荐阅读