简体   繁体   English

如何在Core Data中存储NSDate?

[英]How to store NSDate in Core Data?

When generating Core Data subclasses I check to use primitive data type in Core Data storage. 在生成Core Data子类时,我检查在Core Data存储中使用原始数据类型。

在此输入图像描述

Which NSTimeInterval representation should I convert from NSDate ? 我应该从NSDate转换哪个NSTimeInterval表示? Or it does not matter, just use appropriately when reading / writing the same managed object attribute? 或者无关紧要,只需在读/写相同的托管对象属性时正确使用?

I prefere to use like: mo.creationDate = date.timeIntervalSinceReferenceDate 我更喜欢使用: mo.creationDate = date.timeIntervalSinceReferenceDate

iOS's reference date counts from : 1 January 2001, GMT. iOS的参考日期为:2001年1月1日,GMT。
Unix Time Stamp reference date counts from : Jan 01 1970, UTC Unix时间戳参考日期计算自:1970年1月1日,UTC

If this is a completely offline app you can use the timeIntervalSinceReferenceDate and store the value directly. 如果这是一个完全脱机的应用程序,您可以使用timeIntervalSinceReferenceDate并直接存储该值。

But, if you are going to sync up with a server then generally, it is preferable to send the data to server as a unix time stamp. 但是,如果您要与服务器同步,那么通常最好将数据作为unix时间戳发送到服务器。 Because a desktop uses unix time Stamp as default. 因为桌面使用unix时间戳作为默认值。

So, in the second case you can either choose to save the date directly as a UnixTimeStamp and convert it for local use using a getter in Model Class (refer : @VladZ) or You can save it as iOS's reference date and convert it to UnixTimeStamp each time you send it to server. 因此,在第二种情况下,您可以选择将日期直接保存为UnixTimeStamp,并使用Model Class中的getter将其转换为本地使用(请参阅:@VladZ)或者您可以将其保存为iOS的参考日期并将其转换为UnixTimeStamp每次发送到服务器。

使用 - timeIntervalSince1970并将此值保存在CoreDate中

mo.creationDate = [NSNumber numberWithDouble:timeInterval];

You're adding a time interval, that it's not an object of type NSDate. 您正在添加时间间隔,它不是NSDate类型的对象。

Try to add a NSDate with the desired time interval: 尝试添加具有所需时间间隔的NSDate:

Check this out 看一下这个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM