views:

89

answers:

2

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?

+2  A: 

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.

Chris Garrett
Thanks, much easier than I thought!
Joshua
+2  A: 

You can set the default value inside of the model to 'TODAY' or 'NOW' and it will automatically be set when you create an instance of that entity.

Marcus S. Zarra
Ah, that's a nice little trick to know. I didn't think it would accept a string in the default field for an NSDate. Thanks (new correct answer)!
Joshua
@Marcus, I have noticed that on the iPhone (not tested on Mac) that "today" or "now" evaluate to the compile date, not the runtime date. http://iphonedevelopment.blogspot.com/2009/07/core-data-default-dates-in-data-model.html seems to back this up. I was thinking "awesome" when I saw your comment, but I noticed it doesn't work as I expected.
Brent Priddy