CoreData’s default date value
CoreData is a powerful system available to Cocoa developers. Yet, with all of its inherent power somewhat mundane tasks still need a bit of customization love. Amoung these items are default values for managed object attributes. In particular, the default value for date type attributes usually need some customization.
Within the core data modeler the default value for a date type attribute exists as a rather ambiguous empty text field. Documentation on what can be entered into this text field are, shall we say, rather hard to come by. With a bit of experimentation and extensive Googling it can be found that the values “now’”and “today” can be entered into the field (quotes needed).

As expected this will automatically fill in the current date as the default value for the attribute. However, there seems to be little difference between “now” and “today” in that the time portion of the date is always set to 12:00:00. You might expect the “today” value to work this way but it would certainly be nice if “now” truly meant ‘right now’ and not ‘now more or less kinda’. But, if this will work for you then you’re done.
If having a fixed date is what you need then you could always provide a natural language string as defined in the documentation for [NSDate dateWithNaturalLanguageString]. In fact, ALL of the following default values for a date type seem to work:



Yes, you read that right. Even “last Tuesday at dinner” works here:

Amazingly, we can easily get the time for last Tuesdays dinner but the current time is a mystery. Leave it up to us software developers to be focused on meals.
In the end if you need to set the default value of a date attribute to the current date and time you’ll need to subclass NSManagedObject. It’s an easy thing to do so here it is:
First, define a subclass of NSManagedObject. We’ll call this class ‘BlogEntryEntity’. Next, we need to override the NSManagedObject method ‘awakeFromInsert’.
- (void) awakeFromInsert
{
[super awakeFromInsert];
[self setValue:[NSCalendarDate date] forKey:@"postDate"];
}
As you can see it’s just two lines of code after overriding the method. Be sure to invoke the superclass’s method first as per the NSManagedObject docs. To make things simple we make use of NSManagedObjects excellent KVC abilities and use the setValue:forKey: method. Finally, we need to set the class of our BlogEntry managed object. This is done by simply changing the ‘Class’ field of the class attributes in the core data modeler from NSManagedObject to BlogEntryEntity.

That’s it. Now, whenever an instance of BlogEntry is created the postDate attribute is set to the current date and time. Have fun, and let us know in the comments if you find any other interesting default values that work.



1 Comment