Say I have an NSManagedObject subclass called Item. Whenever an item instance is saved I want to update a property based on a computed value from a transient property. I know I can update the property whenever the transient property changes but for this question, assume there’s a good reason I don’t want to do that.
I tried to do this in the willSave method as follows:
- (void)willSave
{
self.computedProperty = [self computedValueFromTransientProperty];
}
This causes a crash when saving the context. If I move the code out of willSave and set the property explicitly before invoking save it works fine. The apple docs say you should avoid changing managed object properties in willSave.
QUESTION: is there a good way to build functionality into a NSManagedObject subclass so a property can be updated just before save w/o having to explicitly set the property from outside the class and w/o setting the property every time the transient property changes?
You’re able to set persistent properties from
willSave, you just have to be more careful about it.From the
willSavedocs:So, what’s happening is you’re changing
computedProperty, which is causingwillSaveto be called again, which changescomputedPropertywhich callswillSaveagain, until your program crashes.To fix this you need to check whether or not
computedPropertyneeds to be set again:This will mean that
computedValueFromTransientPropertywill get called twice, so you might not want to do this if the method is computationally expensive.Another option is to use the primitive set method which will mean
willSavewon’t get called twice, but might have side affects depending on how your app interacts with Core Data: