iOS核心数据:未通知viewContext有关背景上下文的更改

时间:2017-09-01 09:29:14

标签: ios core-data

我使用此代码删除给定实体的所有数据:

    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通知)。有人知道为什么吗?

0 个答案:

没有答案