如何同步主要和后台核心数据线程?

时间:2019-05-11 11:09:44

标签: ios swift multithreading core-data nsmanagedobjectcontext

我将数据保存到后台线程中的核心数据中

class CoreDataHelper: NSObject {
    static let sharedInstance = CoreDataHelper()

    private func managedObjectContext() -> NSManagedObjectContext {
        return (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    }

    func saveNewFood(foodName: String) {
        let context = managedObjectContext()
        let privateContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)

        privateContext.persistentStoreCoordinator = context.persistentStoreCoordinator
        privateContext.perform {
            let food = Food(context: context)

            food.name = foodName
            food.isInTheFridgeNow = true

            do {
                try context.save()
            } catch let error {
                print(error.localizedDescription)
            }
        }
    }
}

我有在主线程中获取数据的功能:

func fetchFoodsThatsInTheFridgeNow() -> [Food] {
    let fetchRequest: NSFetchRequest<Food> = Food.fetchRequest()
    let sortDescriptor = NSSortDescriptor(key: "name", ascending: true)
    var foods: [Food] = []

    fetchRequest.predicate = NSPredicate(format: "isInTheFridgeNow == YES")
    fetchRequest.sortDescriptors = [sortDescriptor]

    do {
        foods = try managedObjectContext().fetch(fetchRequest)
    } catch let error {
        print(error.localizedDescription)
    }

    return foods
}

保存新食物后,我想立即在VC中查看新食物列表(无需关闭应用程序并再次运行)。如何实现?

1 个答案:

答案 0 :(得分:0)

您可以观察ContextWillSave通知,然后您可以访问任何类中的新更新,插入和删除的对象。 https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/CoreData/ChangeManagement.html