我想对修改后的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
。我该如何实现?