I have a lot of date fields in my database model. CoreData allows to use NSDate or TimeInterval to save dates depending on "Use Scalar Type" option.
However both these options are bad for me since I want to use dates as Date objects. Since NSDate is not implicitly convertible to Date I have to cast/convert values to Date or to implement a lot of custom setters/getters in my NSManagedObject classes.
I have tried to use ValueTransformer but it does not work with non-@objc classes like Date.
So is there a simple way to save and get Date values to/from CoreData?


Yes, but you might not like it. If you declare the property using a Core Data "Date" type and let Xcode generate the
NSManagedObjectsubclass for you, the property will be an@NSManagedproperty of typeNSDate. As you've figured out, you'd then have to deal withDatevs.NSDateyourself.If you don't let Xcode generate the subclass for you (in Xcode 8 set "Codegen" to "Manual/None"), you can declare the Core Data "date" property as something like
It'll just work. You can read and write
Datevalues, and Core Data will do the right thing. But you become completely responsible for the code in theNSManagedObjectsubclass. You'll have to create the whole class. If you update the Core Data model, you'll have to update the class as well. Whether this seems worthwhile is up to you but it's the only solution that seems to exist right now.Update: In Xcode 9, generated code uses
Date, so this shouldn't be necessary any more.