NSManagedObject will not be called for an invalid object

I have an NSManagedObject class with the updatedOn attribute. I was hoping to implement the logic to set its value in the willSave class. When I tried to do this, I found that willSave was never called in my instances of this class.

After some research, I decided that the willSave method willSave not called for newly created instances where updatedOn not initialized with any value. Since this attribute has not been set as optional, verification is not performed, and the willSave method willSave called only if the instance is valid.

My question is: is there any best practice for this kind of thing? Do I need the updatedOn attribute updatedOn be optional to get around this? Or should I implement the awakeFromInsert method of my class to set the initial value there, and then overwrite that value when the willSave method is ultimately called? Or is there a simpler approach that makes more sense?

+4
source share
1 answer

The willSave documentation contains a reference to using the method for time stamping, and despite the mention of some complications associated with changing property values ​​and recursion, it does not specifically warn about this use. Therefore, I think, based on this fact, this can be considered a reasonable place for applying this function.

However, the documentation refers to using NSManagedObjectContextWillSaveNotification to calculate the common timestamp, so this may be an alternative place for this to work. To search for objects that require time stamping, you need to manually check the insertedObjects and updatedObjects for managedObjectContext , but based on some quick tests, it seems to be called before the validation steps, so you will be able to set the required property here.

If you decide to stick to willSave , then you probably have 3 options.

  • Required property with a default value in your model.
  • A required property with a set of properties on awakeFromInsert or another suitable point.
  • Additional property.

I think that any of the options is a reasonable choice, but I think that if it were me, I would choose NSManagedObjectContextWillSaveNotification only because of the complications of setting property values ​​to willSave.

+6
source

All Articles