我对Swift还是相当陌生,希望有人知道答案-我尝试的任何方法似乎都无效!
我有一个Swift应用程序,该应用程序具有一个名为“ Drink”的Core Data实体,该实体具有2个键:一个日期和一个名为“ drinkWater”的实体,当按下按钮时,该实体存储值“ 1”。
我正在尝试编写一个单独的函数,在该函数中,我可以检查是否存在今天的日期条目,如果存在,请执行一个操作(在这种情况下,请更改imageview)。
我意识到以下并不是答案,但就我所知!基本上,我可以根据DrinkWater的值来获取所有条目(这需要在我猜的日期之前?),并且可以将今天的所有日期打印到控制台上。现在我被卡住了...
private func updateMyImageView() {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Drink")
request.predicate = NSPredicate(format: "drinkWater = %@", "1")
request.returnsObjectsAsFaults = false
do {
let result = try context.fetch(request)
for data in result as! [NSManagedObject] {
print(data.value(forKey: "timestamp") as! Date)
}
} catch {
print("Failed")
}
let dateNow = Date()
print("Date is \(dateNow)")
}
这将返回:
2018-12-29 01:27:27 +0000
日期是2018-12-29 12:21:21 +0000
任何将其全部转换为正确功能的想法将不胜感激!!
答案 0 :(得分:2)
您需要在复合谓词中使用从开始日期到结束日期(午夜至午夜)的日期范围。这是基于类似的question
的解决方案var calendar = Calendar.current
calendar.timeZone = NSTimeZone.local
let dateFrom = calendar.startOfDay(for: Date())
let dateTo = calendar.date(byAdding: .day, value: 1, to: dateFrom)
let fromPredicate = NSPredicate(format: "timestamp >= %@", dateFrom as NSDate)
let toPredicate = NSPredicate(format: "timestamp < %@", dateTo! as NSDate)
let waterPredicate = NSPredicate(format: "drinkWater = %@", "1")
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Drink")
request.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [waterPredicate, fromPredicate, toPredicate])
答案 1 :(得分:0)
感谢您的所有帮助。我已经全部工作了。我的最终代码是:
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
var calendar = Calendar.current
calendar.timeZone = NSTimeZone.local
let dateFrom = calendar.startOfDay(for: Date())
let dateTo = calendar.date(byAdding: .day, value: 1, to: dateFrom)
let fromPredicate = NSPredicate(format: "timestamp >= %@", dateFrom as NSDate)
let toPredicate = NSPredicate(format: "timestamp < %@", dateTo! as NSDate)
let waterPredicate = NSPredicate(format: "drinkWater = %@", "1")
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Drink")
request.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [waterPredicate, fromPredicate, toPredicate])
do {
let result = try context.fetch(request)
for data in result as! [NSManagedObject] {
print(data.value(forKey: "timestamp") as! Date)
drinkMoreButton.setBackgroundImage(UIImage(named: "watericonselected.png"), for: UIControlState.normal)
}
} catch {
print("Failed")
}