-1

I save data to my Core Data in background thread:

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)
            }
        }
    }
}

And I have function that fetch data in Main thread:

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
}

After saving new food, I want to see new foods list in my VC immediately (without close my application and run it again). How to realize it?

Tkas
  • 302
  • 3
  • 14

1 Answers1

0

You can observe ContextWillSave notification and then you have access to newly updated, inserted and deleted objects from any class. https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/CoreData/ChangeManagement.html

cnazk
  • 76
  • 5