Core Data Nstimeinterval Using an Accessor Directly Is Buggy

Core Data NSTimeInterval using an accessor directly is buggy

A scalar property of type NSTimeInterval for a Core Data Date
property represents the time in seconds since the reference date
Jan 1, 2001. The Core Data generated accessor methods transparently
convert between NSTimeInterval and NSDate.

Therefore you set a value using the scalar accessor with

obj.dateLastSynced = date.timeIntervalSinceReferenceDate

and you retrieve the value with

let date = NSDate(timeIntervalSinceReferenceDate: obj.dateLastSynced)

This gives the same results as the Key-Value Coding methods

// Set:
obj.setValueForKey(date, "dateLastSynced")
// Get:
let date = obj.valueForKey("dateLastSynced")

Why is an NSDate in a Core Data managed Object converted to NSTimeInterval?

I get this if I check the "Use scalar properties for primitive data types" checkbox when I'm generating my files.

This is because NSTimeInterval is a double in disguise, whereas NSDate is a class that inherits from NSObject.

Why does a type Date attribute in CoreData turns out to be type TimeInterval in the entity class extension?

The TimeInterval will be the number of seconds since 2001-01-01T00:00:00Z. Xcode generates the property with this type because you have checked the "Use Scalar Type" checkbox in the first screenshot.

You can create a Date from these TimeIntervals like this:

Date(timeIntervalSinceReferenceDate: someTimeInterval)

You should uncheck it, and regenerate the classes. The types will now be NSDate.

However, if you want the Swift Date types, you need another solution. See here.

Difference between dot syntax and valueForKey

It was a problem with the difference in epochs. NSDate uses Jan 1 2001 as an epoch. So when I was getting the value I was using the unix epoch (1970). That gave me a difference in values.

When KVC unwraps and wraps NSTimeInterval with a NSDate object it uses the NSDate 2001 epoch.

So instead of using dateWithTimeIntervalSince1970
I used dateWithTimeIntervalSinceReferenceDate when getting the value.



Related Topics



Leave a reply



Submit