0

is there a way to save multiple CoreData objects on the same day?

let newitem = Record(context: viewContext)
newitem.date = Date()
newitem.totaltime = item.totaltime

and on the same Date() in the next time

totaltime += 200

I used this, but it doesn't work

if !ro.filter({$0.date == Date()}).isEmpty{
}else{
}
jnpdx
  • 45,847
  • 6
  • 64
  • 94
  • Could you explain what you want to do so we can get a better idea? – Visal Rajapakse Sep 26 '21 at 07:39
  • 3
    `Date()` contains more precise information than just day/month/year - up to miliseconds if I’m not mistaken. So when you filter by `Date()` its an entirely different object (representing a different point in time) than the one you had when saving the record. You need to extract only the relevanant components. – Losiowaty Sep 26 '21 at 07:51
  • 1
    I closed this with two links, one for using NSPredicate and one for using for instance filter – Joakim Danielson Sep 26 '21 at 07:59

1 Answers1

0

From what I see, in the .filter{} method, filtering by just Date() won't do.

See the example below,

let now = Date()
var delayedDate: Date!

// Causing a delay of 1 second
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
    delayedDate = Date() // Date after one second
    print("Date now:", now, ", Delayed date:", delayedDate!) // Printing the dates. See that they are not equal
    print(now == delayedDate) // Checking if the dates are equal will result in false
}

This will result in the following

enter image description here

What this means that the date object you are comparing with the ones from CoreData is not equal. You can say that you are trying to equate COMPLETELY different objects.

So what you can do is, use a solution from this link to break a Date() object into components such as date, hour, minute, etc. and then compare the date component with the ones from CoreData. Note that the component conversion needs to be done for the CoreData Dates as well

Visal Rajapakse
  • 1,718
  • 1
  • 9
  • 15