This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private var cancellables = [AnyCancellable]() | |
let cancellable = NotificationCenter.default.publisher(for: .NSManagedObjectContextObjectsDidChange, object: managedObjectContext) | |
.compactMap({ ManagedObjectContextChanges<ColorItem>(notification: $0) }).sink { (changes) in | |
print(changes) | |
} | |
cancellables.append(cancellable) | |
struct ManagedObjectContextChanges<T: NSManagedObject> { | |
let inserted: Set<T> | |
let deleted: Set<T> | |
let updated: Set<T> | |
init?(notification: Notification) { | |
let unpack: (String) -> Set<T> = { key in | |
let managedObjects = (notification.userInfo?[key] as? Set<NSManagedObject>) ?? [] | |
return Set(managedObjects.compactMap({ $0 as? T })) | |
} | |
deleted = unpack(NSDeletedObjectsKey) | |
inserted = unpack(NSInsertedObjectsKey) | |
updated = unpack(NSUpdatedObjectsKey).union(unpack(NSRefreshedObjectsKey)) | |
if deleted.isEmpty, inserted.isEmpty, updated.isEmpty { | |
return nil | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment