我使用此代码删除给定实体的所有数据:
let stack = CoreDataStack.shared
stack.performBackgroundTask { context in
let fetchRequet = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
fetchRequet.predicate = predicate
fetchRequet.resultType = .managedObjectIDResultType
fetchRequet.includesPropertyValues = false
let results: [AnyObject]?
do {
results = try context.fetch(fetchRequet)
} catch {
results = nil
}
if results != nil {
for id in results! {
let object = context.object(with: id as! NSManagedObjectID)
context.delete(object)
}
stack.save(context)
}
}
func performBackgroundTask(_ block: @escaping (NSManagedObjectContext) -> Void) {
self.persistentContainer.performBackgroundTask(block)
}
func save(_ context: NSManagedObjectContext) {
if context.hasChanges {
do {
try context.save()
} catch let error as NSError {
logger.error("Error saving context: \(error)")
context.rollback()
}
}
}
我已设置self.persistentContainer.viewContext.automaticallyMergesChangesFromParent = true
但未通知viewContext有关更改(未触发NSManagedObjectContextDidSave通知)。有人知道为什么吗?