Defining old and new values ​​for modified objects using NSManagedObjectContextWillSaveNotification

I am trying to track object changes in the context of master data by tracking the name of the changed properties along with old and new values.

I registered for NSManagedObjectContextWillSaveNotificationto be notified when a save will occur, and can pull inserted / updated / deleted objects out of context ... Then I can see the changed values ​​using .changedValues.

However, I am having difficulty retrieving old values ​​...

As an example, I have an object that tracks a position, and so one of the changes is returned:

po [obj changedValues]
{
    originX = 260;
    originY = 180;
}

This gives me new values ​​for properties that have been changed on the object. To try to get the old values, I use changedValuesForCurrentEventwhich, according to the docs, should return

"a dictionary containing keys and old values ​​of constant properties that have changed since the last publication NSManagedObjectContextObjectsDidChangeNotification"

However, when I try to do this, it returns empty ...:

po [obj changedValuesForCurrentEvent]
{
}

How can I capture old and new values?

+4
source share
3 answers

. NSManagedObjectContextObjectsDidChangeNotification , , . NSManagedObjectContextWillSaveNotification . , :

  • β†’ NSManagedObjectContextObjectsDidChangeNotification, changedValuesForCurrentEvent, , .
  • . NSManagedObjectContextWillSaveNotification . changedValuesForCurrentEvent, , . . , . , .

, , , :

  • NSManagedObjectContextObjectsDidChangeNotification. - - (, NSDictionary). , NSManagedObjectContextWillSaveNotification , , . ...
  • NSManagedObjectContextWillSaveNotification, . , . , , , , , .
+8

, , , . commitValues ​​(forKeys:) changedValues ​​(). NSManagedObjectContextObjectsDidChangeNotification .

, :

// For some reason, the Swift compiler chokes on the type of object.changedValues().keys.
// It should be of type [String], but it complains that it is of type `Dictionary<String, Any>.Keys`
// which is useless. Ah, the joys of Apple programming...
// Work around that like so:
var changedKeys = [String]()
for (key, _) in object.changedValues() {
    changedKeys.append(key)
}
let oldData = object.committedValues(forKeys: changedKeys)
0

, "changedValuesForCurrentEvent" , "NSManagedObjectContextWillSaveNotification" .

"changedValuesForCurrentEvent" - , , - "userInfo". , NSManagedObjectContextObjectsDidChangeNotification ", .

-1

Source: https://habr.com/ru/post/1539034/


All Articles