Swift中的核心数据通知

时间:2015-06-16 09:56:59

标签: ios swift core-data

我试图在Core Data通知中从userInfo获取更新的对象。我在Objc中工作得很好,但在Swift中证明它很难。我尝试过几种方式获取数据,但这是我目前的实现,总是返回nil:

noti.userInfo?[NSUpdatedObjectsKey]

如何获取数据?这是工作的Objc代码:

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

1 个答案:

答案 0 :(得分:2)

注册通知。当对象被去除时,不要忘记删除。

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

这是获取更新对象的方法。

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