I have an NSManagedObject class with a updatedOn attribute. I was hoping to implement the logic to set its value in the class’s willSave method. When I tried to do this, I found that willSave was never being called on my instances of this class.
After some investigation, I determined that the willSave method was not being called for newly created instances, where updatedOn was not initialized to any value. Because this attribute was not set to be optional, the validation fails and apparently the willSave method only gets called if the instance is valid.
My question is this: Is there a best practice for doing this kind of thing? Do I need to make the updatedOn attribute optional to work around this? Or should I implement the awakeFromInsert method of my class to set an initial value there, and then overwrite that value when the willSave method eventually gets called? Or is there some simpler approach that makes more sense?
The
willSavedocumentation makes reference to using the method for time stamping and despite mentioning some complications around changing property values and recursion, it doesn’t warn specifically against this use. So I guess, based on that fact, it could be considered a reasonable place to put this functionality.The documentation does, however, refer to the use of the
NSManagedObjectContextWillSaveNotificationfor calculating a common timestamp, so perhaps this would be a alternative location for this work. It would require manual inspection of theinsertedObjectsandupdatedObjectscollections on themanagedObjectContextto locate the objects that need time stamping, but based on some quick tests it does seem to be called before the validation steps so you would have an opportunity to set the required property here.If you chose to stick with
willSavethen I guess you have 3 options.I think any of the options are reasonable choices, but I think if it were me I would probably chose the
NSManagedObjectContextWillSaveNotificationjust because of the complications with setting property values in willSave.