Trouble registering for Static notifications (for SwiftData.ModelContext)

Testing out the new SwiftData library and am a bit stuck trying to subscribe to notifications. According to docs it has a didSet and willSet notification but I've yet to be able to successfully subscribe.

When I generically run the following I am able to find notifications when inserts occur:

class NotificationObserver {
    init() {
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(printAllNotifications),
            name: nil,
            object: nil)
    }

    @objc func printAllNotifications(_ note: Notification) {
        print(note)
    }
}

This triggers a variety of notifications:

NSNotificationName(_rawValue: _NSManagedObjectContextPrivateDidMutateObjectIDsNotification)
NSNotificationName(_rawValue: NSPersistentStoreRemoteChangeNotification)
NSNotificationName(_rawValue: _NSManagedObjectContextDidSaveObjectIDsPrivateNotification)
NSNotificationName(_rawValue: NSManagedObjectContextDidSaveObjectIDsNotification)
NSNotificationName(_rawValue: _NSManagedObjectContextDidSaveObjectIDsPrivateNotification)
NSNotificationName(_rawValue: NSManagedObjectContextDidSaveObjectIDsNotification)
NSNotificationName(_rawValue: NSManagingContextDidSaveChangesNotification)

But if I try to subscribe directly for ModelContext.didSave, it never fires, for example:

        Task {
            for await notification in NotificationCenter.default.notifications(named:ModelContext.didSave) {
                print(notification.name)
            }
        }

I've tried filling in object with ModelContext.self, no luck, and also using addObserver but feeling pretty lost on how to get this working.

Reference: didSave | Apple Developer Documentation

2 Likes

Did you ever find a solution to this? Running into the same challenge. Can't find a way to catch updates before save so I can sync back to server.