NSManagedObject's willSave not being called for invalid object

core-data, ios, iphonecoredatarecipes, objective-c

Solution

The `willSave` documentation 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 `NSManagedObjectContextWillSaveNotification` for calculating a common timestamp, so perhaps this would be a alternative location for this work. It would require manual inspection of the `insertedObjects` and `updatedObjects` collections on the `managedObjectContext` to 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 `willSave` then I guess you have 3 options.

- A required property with a specified default value in your model.

- A required property with the property set on awakeFromInsert or some other suitable point.

- An optional property.

I think any of the options are reasonable choices, but I think if it were me I would probably chose the `NSManagedObjectContextWillSaveNotification` just because of the complications with setting property values in willSave.

Problem

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?

Original source