Notifications not working on ModelContext

I've been testing out SwiftData but haven't bee able to get ModelContext notifications working. I've tried both an objc observer and for await patterns but it never fires. If I listen for the older nsmanagedcontext notifications they are firing, but I am hoping that the new ones give an ID instead of an objectId. Has anyone got these working?

Attempt 1:

class NotificationObserver {
    init() {
        let didSaveNotification = ModelContext.didSave
        NotificationCenter.default.addObserver(self, selector: #selector(didSave(_:)),
                                               name: didSaveNotification, object: nil)
    }
    @objc func didSave(_ notification: Notification) {
        print(notification.name)
    }
}

Attempt 2:

class NotificationObserver {
    init() {
        let didSaveNotification = ModelContext.didSave
        Task {
            for await note in NotificationCenter.default.notifications(named: didSaveNotification) {
                print(note)
            }
        }
    }    
}
Post not yet marked as solved Up vote post of pnewelljr Down vote post of pnewelljr
1.3k views

Replies

Your object is set to nil, but shouldn't it be set to ModelContext context?

  • When nil it should apply to any ModelContext. You only supply the object if you just one notifications of one instance of ModelContext.

Add a Comment

Try this in your view controller to observe remote change notifications.

NotificationCenter.default.addObserver(self,
                           selector: #selector(updateView(_ :)),
                           name: .NSPersistentStoreRemoteChange,
                           object: nil)

@pnewelljr any luck with this?

facing same issue, anyone have any luck?

This seems to work:

NotificationCenter.default.notifications(named: Notification.Name.NSManagedObjectContextDidSave)

This works even better:

NotificationCenter.default.notifications(named: Notification.Name.NSManagedObjectContextObjectsDidChange)

Looks like a bug needs filed here. Appears that the NSManagedObjectContextObjectsDidChange is likely what ModelContext.didSave should be triggering, as the object in the notification is the ModelContext instance:

(lldb) po notif
▿ name = NSObjectsChangedInManagingContextNotification, object = Optional(SwiftData.ModelContext), userInfo = Optional([AnyHashable("updated"): Set([SwiftData.ModelContext.AnyPersistentObject(boxed: Redacted.Redacted)])])
  - name : "NSObjectsChangedInManagingContextNotification"
  ▿ object : <ModelContext: 0x281632e50>
  ▿ userInfo : 1 element
    ▿ 0 : 2 elements
      ▿ key : AnyHashable("updated")
        - value : "updated"
      ▿ value : 1 element
        ▿ 0 : AnyPersistentObject
          ▿ boxed : <Redacted: 0x280e545a0>