xcode Iphone 核心数据:日期默认值作为当前日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3769771/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Iphone Core Data: Date Default Value as Current date
提问by Rupertius
Im using Core data. I have an entity with an attribute of type Date. Is there a way I can set Default Values as Current Date? (Like entering 'CURRENTDATE' or something in default value of the attribute?)
我正在使用核心数据。我有一个具有日期类型属性的实体。有没有办法可以将默认值设置为当前日期?(比如在属性的默认值中输入“CURRENTDATE”或其他内容?)
Thanks
谢谢
回答by Bill Garrison
You could use "now" in the model, but Core Data evaluates that at compile time, not runtime. You'll get the date of compilation stored in your model defaults, which is probably not what you want:
您可以在模型中使用“now”,但 Core Data 在编译时而不是运行时评估它。您将获得存储在模型默认值中的编译日期,这可能不是您想要的:
http://iphonedevelopment.blogspot.com/2009/07/core-data-default-dates-in-data-model.html
http://iphonedevelopment.blogspot.com/2009/07/core-data-default-dates-in-data-model.html
The most reliable way to ensure a default property value of the current date is to override -awakeFromInsert
in an NSManagedObject subclass and assign the current date there.
确保当前日期的默认属性值的最可靠方法是-awakeFromInsert
在 NSManagedObject 子类中覆盖并在那里分配当前日期。
- (void) awakeFromInsert
{
[super awakeFromInsert];
self.date = [NSDate date];
// or [self setPrimitiveDate:[NSDate date]];
// to avoid triggering KVO notifications
}
Note: If you're making use of nested managed object contexts (or UIManagedDocument), the above will not work as expected. This advice only applies when using single managed object contexts.
注意:如果您使用嵌套的托管对象上下文(或 UIManagedDocument),则上述内容将无法按预期工作。此建议仅适用于使用单个托管对象上下文时。