0
votes

I have a chat app, that works on the main queue, and I want to improve performance by creating a parent and child managed object context where the parent is on the main queue and child is on a private queue. Because when I send a lot of messages at once the UI slows down a little!

the problem I am having is that I automatically generated my coredata stack. and I have no idea how to even access my managed object context. Could somebody give me a bit of advice on how to get started.

   lazy var persistentContainer: NSPersistentContainer = {
    let container = NSPersistentContainer(name: "Reveal_Swift_3")
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? {

            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
    })
    return container
}()

// MARK: - Core Data Saving support

func saveContext () {
    let context = persistentContainer.viewContext
    if context.hasChanges {
        do {
            try context.save()
        } catch {
            let nserror = error as NSError
            fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
        }
    }
}
2

2 Answers

0
votes

Use persistentContainer.viewContext for your UI stuff and persistentContainer.performBackgroundTask(block:) for background tasks.

0
votes

Use:

                 persistentContainer.newBackgroundContext() 

Instead of:

                  persistentContainer.viewContext()

newBackgroundContext() creates a private managed context.

This is how you can create the context:

    var privateUserContext : NSManagedObjectContext {
        get {
            return userPersistentContainer.newBackgroundContext()
        }
    }

And every time you use it you can save it this way.

                    do{
                         try privateUserMOC.save()

                    }
                    catch{
                         print("Error")
                    }

This did it for me.... good luck!