wnagrodzki / iOSProgrammingGuidelines

2 stars 0 forks source link

Wrappers around Notifications #23

Open wnagrodzki opened 5 years ago

wnagrodzki commented 5 years ago
extension Notification {

    public struct ManagedObjectContextDidSave {

        public var insertedObjects: Set<NSManagedObject> { return notification.objects(for: NSInsertedObjectsKey) }
        public var updatedObjects: Set<NSManagedObject> { return notification.objects(for: NSUpdatedObjectsKey) }
        public var deletedObjects: Set<NSManagedObject> { return notification.objects(for: NSDeletedObjectsKey) }
        private let notification: Notification

        fileprivate init(notification: Notification) {
            precondition(notification.name == .NSManagedObjectContextDidSave)
            self.notification = notification
        }
    }

    public func asManagedObjectContextDidSave() -> ManagedObjectContextDidSave {
        return ManagedObjectContextDidSave(notification: self)
    }
}

extension Notification {
    fileprivate func objects(for key: String) -> Set<NSManagedObject> {
        return userInfo?[key] as! Set<NSManagedObject>? ?? []
    }
}