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 TimeInterval
s 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
Draw Polyline Using Google Maps in Custom View with Swift 3
Googlemap API Gives Wrong Coordinates for Direction Between Two Points
How Is a Swift Cgvector Created with Dx and Dy (Derivative)
Force Wkwebview to Show Mobile Version
Creating a First Launch Viewcontroller
How to Make Collage of Images According to Different Shapes
Implementing Codable for UIcolor
How to Print Name of The Day of The Week
iOS - Emphasise with Bold Strings in Localizable.Strings
iOS Add Button to Widget Extension
Gkmatchmaker Invite Handler Deprecated
Runtime Error When Using Corefoundation Objects in a Swift Nsobject Subclass
Collide Type Source Error - Spritekit Swift Game
How Has The Nsindexpath Initialization Changed in Swift3
Parse Cloud - Livequeries - iOS Client Doesn't Work
Ld: Library Not Found for -Ldoubleconversion React Native 0.59
How to Fix Crash When Tap to Select Row After Scrolling The Tableview