将Swift的Date与CoreData一起使用 [英] Use Swift's Date with CoreData

查看:95
本文介绍了将Swift的Date与CoreData一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据库模型中有很多日期字段。 CoreData允许使用NSDate或TimeInterval来保存日期,具体取决于使用标量类型选项。

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.

但是,这两个选项都对我不利,因为我想将日期用作日期对象。由于NSDate不能隐式转换为 Date ,因此我不得不将值强制转换/转换为 Date 或实现很多自定义我的NSManagedObject类中的setters / getters。

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.

我尝试使用 ValueTransformer ,但不适用于非- @objc类,例如 Date

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?

推荐答案

是,但是您可能不喜欢它。如果您使用Core Data日期类型声明属性,并让Xcode为您生成 NSManagedObject 子类,则该属性将为<$ NSDate 类型的c $ c> @NSManaged 属性。如您所知,您将不得不自己处理 Date NSDate 的问题。

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.

如果您让Xcode为您生成子类(在Xcode 8中将 Codegen设置为 Manual / None),则可以声明核心数据的日期属性,例如

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?

它会正常工作。您可以读写 Date 值,Core Data将做正确的事情。但是您要完全负责 NSManagedObject 子类中的代码。您必须创建整个课程。如果您更新核心数据模型,则还必须更新该类。这是否值得,取决于您,但这是目前似乎唯一的解决方案。

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.

更新:在Xcode 9中,生成代码使用 Date ,因此不再需要。

Update: In Xcode 9, generated code uses Date, so this shouldn't be necessary any more.

这篇关于将Swift的Date与CoreData一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆