Use Swift's Date with CoreData

后端 未结 2 1428
孤独总比滥情好
孤独总比滥情好 2021-02-13 16:26

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 b

相关标签:
2条回答
  • 2021-02-13 17:07

    Yes, but you might not like it. If you declare the property using a Core Data "Date" type and let Xcode generate the NSManagedObject subclass for you, the property will be an @NSManaged property of type NSDate. As you've figured out, you'd then have to deal with Date vs. NSDate yourself.

    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

    @NSManaged public var timestamp: Date?
    

    It'll just work. You can read and write Date values, and Core Data will do the right thing. But you become completely responsible for the code in the NSManagedObject subclass. 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.

    0 讨论(0)
  • 2021-02-13 17:07

    There is a workaround here that works, if you set it as transformable and set its custom class to Date it simply works.

    0 讨论(0)
提交回复
热议问题