How to get old and new value of property of NSPropertyDescription

Viewed 210

I have a CoreData stack set up, able to retrieve the edit history for specific objects and so forth. I can even identify which property changed. However I'm struggling with getting the old and new value of the property. See my code below. Is this even possible? If so, how?

func apply(_ changeItem: NSPersistentHistoryChange) {
    switch changeItem.changeType {
    case .update:
        guard let updatedProperties = changeItem.updatedProperties else { break }

        updatedProperties.forEach { (property) in
            // Get old and new value here
        }
    case .insert:
        // ...
    }
    // ...

}
2 Answers

Problem I was facing:

  • I couldn't identify the record to update in the destination store.

Workaround:

  • Use an identifier field in the Entity
  • That way you can query based on the identifier and update destination store with the new values
  • identifier will not / should not change after insertion

Maybe this isn’t your case but as I guess you have NSPersistentHistoryChange from NSPersistentHistoryTransation. In this case you can merge whole changes from that transaction all at once by merging it into context Example:

 guard let userInfo = transaction.objectIDNotification().userInfo else { return }           
NSManagedObjectContext.mergeChanges(fromRemoteContextSave: userInfo, into: [context])

In your specific secnerio I didn't found how to find old value in NSPersistentHistoryChange. Maybe userInfo contains this information

Related