Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting Default Value of NSDate to Today

In my Core Data model I have a property which is a NSDate, the user can change it and it is optional. I would like to set this property's default value as today, I saw no way to do this in the Core Data Model so I subclassed NSManangedObject and added this code to the implementation file.

- (NSDate *)date {
    return [NSDate date];
}

This seemed to work however the Date is always todays date, even when the user changes it, it goes back to today. And if an object was created yesterday it will change the date to today, so that all the objects date will be today.

How do I get around this, do the default date is today by the user can still change it?

like image 250
Joshua Avatar asked Aug 13 '10 11:08

Joshua


1 Answers

Is "date" the name of the property as well? If so, then your code will always return the current date, since you would have overridden the property method.

To set a custom default value for a property, you can override the awakeFromInsert method. Inside that method, set the property value to [NSDate date]. See the docs for NSManagedObject for a description of this method.

like image 194
Chris Garrett Avatar answered Oct 06 '22 01:10

Chris Garrett