CoreData:如何在NSManagedObjectContextObjectsDidChange中创建和保存对象?

时间:2019-01-08 09:38:41

标签: ios swift core-data

我想对修改后的NSManagedObjects做出反应,因此我设置了一个观察者:

NotificationCenter.default.addObserver(forName: NSNotification.Name.NSManagedObjectContextObjectsDidChange, object: nil, queue: nil) { notification in
    ...
}

但是我还没有找到解决方案,如何在该块中创建对象。

NotificationCenter.default.addObserver(forName: NSNotification.Name.NSManagedObjectContextObjectsDidChange, object: nil, queue: nil) { notification in
    let context = notification.object as! NSManagedObjectContext
    context.perform {
        let insertedObjects = notification.userInfo?[NSInsertedObjectsKey] as? Set<NSManagedObject> ?? Set<NSManagedObject>()
        // insertedObjects are empty (outside of context.perform they are NOT EMPTY
    }
}

当我不使用context.perform时,也会得到attempt to recursively call -save: on the context aborted。我该如何实现?

0 个答案:

没有答案