Provides an opportunity to add code into the life cycle of the managed object when it is about to be saved.
- iOS 3.0+
- macOS 10.4+
- tvOS 9.0+
- watchOS 2.0+
- Core Data
This method can have “side effects” on persistent values. You can use it to, for example, compute persistent values from other transient or scratchpad values.
If you want to update a persistent property value, you should typically test for equality of any new value with the existing value before making a change. If you change property values using standard accessor methods, Core Data will observe the resultant change notification and so invoke
will again before saving the object’s managed object context. If you continue to modify a value in
will will continue to be called until your program crashes.
For example, if you set a last-modified timestamp, you should check whether either you previously set it in the same save operation, or that the existing timestamp is not less than a small delta from the current time. Typically it’s better to calculate the timestamp once for all the objects being saved (for example, in response to an
If you change property values using primitive accessors, you avoid the possibility of infinite recursion, but Core Data will not notice the change you make.
The sense of “save” in the method name is that of a database commit statement and so applies to deletions as well as to updates to objects. For subclasses, this method is therefore an appropriate locus for code to be executed when an object deleted as well as “saved to disk.” You can find out if an object is marked for deletion with