Friday, July 10, 2009

Core Data Default Dates in Data Model

I'm leaving this blog entry, but do not use this tip - there is a flaw in it

When creating a managed object model using Xcode's Data Model Editor, I knew that there was a way to specify a default value for a date attribute that would cause it to default to the current date and time. It's one of those things I need to do about twice a year and can never, ever remember how it's done. Apple's documentation didn't yield an answer (it might be in there, but it's not easy to find). Yes, you can create a custom subclass of NSManagedObject and set the value in awakeFromInsert:, but for those situations where you don't want to subclass, or don't feel like it, I knew there was a way and it was frustrating me that I couldn't remember it or find it.

Thanks to Twitter, I got the answer, and it's a cooler answer than I remembered. The Default field for date attributes will interpret natural language strings put in quotes. It appears to be that anything that NSDate's natural language parser can handle, the date attribute's default field can handle. "Tomorrow", "Today", "Now", "Yesteday at Breakfast".

WHOAH: After a user comment alerted me to this, I tested it out and sure enough, the natural language string entered into the default field is actually determined at compile time, not at runtime, so 'today' will always result in the same date. Do not use this technique!

via Shane Crawford

No comments:

Post a Comment