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

4 comments:
Jeff, I seem to remember being pleased to find this when i first starting using Core Data BUT after finding that "today" worked perfectly the first day I was disappointed to find that it was the same date the next day and the next. It seems that the editor interpreted the natural language string and not core data at runtime as I'd perhaps naively expected.
You are right, I just confirmed it. Thanks for the heads up!
This strikes me as rather funny.
mhoy:
It's a riot, actually. It goes to show you that if something isn't documented, it's potentially unsafe to use.
Jeff
Post a Comment