user470763
user470763

Reputation:

Core Data notifications in Swift

I'm trying to get the updated objects from userInfo in a Core Data notification. I have this working fine in Objc but it's proving difficult in Swift. I've tried getting the data in a few ways but this is my current implementation which is always returning nil:

noti.userInfo?[NSUpdatedObjectsKey]

How do I get the data? This is the working Objc code:

NSArray *updatedObjects = [[noti.userInfo objectForKey:NSUpdatedObjectsKey] allObjects];

Upvotes: 2

Views: 1276

Answers (1)

christopher.online
christopher.online

Reputation: 2774

Register for notification. Do not forget to remove when object is deinited.

NotificationCenter
   .default
   .addObserver(self,
                selector: #selector(contextSaved(_:)),
                name: .NSManagedObjectContextDidSave,
                object: yourManagedObjectContext)

This is how you get the updated objects.

@objc func contextSaved(_ notification: Notification) {
        if let updated = notification.userInfo?[NSUpdatedObjectsKey] as? Set<NSManagedObject>, updated.count > 0 {
            print("updated: \(updated)")
        }
    }

Upvotes: 3

Related Questions