Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iphone Core Data: Date Default Value as Current date

Tags:

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?)

Thanks

like image 269
Rupertius Avatar asked Sep 22 '10 13:09

Rupertius


1 Answers

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:

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.

- (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.

like image 177
Bill Garrison Avatar answered Oct 15 '22 13:10

Bill Garrison