0

I have a long CoreData process (GlobalData.shared.resetData function) that takes around 4 seconds and I want to present a loading indicator.

Both action (core data process and showing loading indicator) must run in Main Queue,

Do you know why the showing loading indicator always happened after CoreData process?

@IBAction func resetTapped(_ sender: UIButton) {
    tableView.backgroundColor = .green
    showLoading(loadingText: nil)         
    GlobalData.shared.resetData(completion: {
        self.refreshGlobalData()
    })
}

I added that line to change table background color for testing. Background color always changed after core data process (GlobalData.shared.resetData function).

Vahid
  • 3,352
  • 2
  • 34
  • 42
  • This is starting from the incorrect assumption that CoreData needs to load on the main thread: https://stackoverflow.com/questions/10659815/loading-coredata-in-a-background-thread – ekscrypto Jul 30 '18 at 11:11
  • @ekscrypto, I configure all the app to run `coredata` on main thread. there is not a solution for my issue without change core data thread configuration?! – Vahid Jul 30 '18 at 11:14
  • running a 4-seconds process on the main thread is a seriously bad idea. You will want to run that CoreData on a background thread. No questions there. – ekscrypto Jul 30 '18 at 11:16

1 Answers1

0

When you change the background color like that, you're changing the "model", but you won't see the results until the next time the main thread redraws, which won't happen until your code relinquishes control of the run loop (finishes running). You could try dispatch_async-ing the Core Data op, which may allow the run loop to draw before starting your operation. But really, as commenters have mentioned, don't do something that takes four seconds on the main thread.

ipmcc
  • 29,581
  • 5
  • 84
  • 147
  • Put core data process on another queue will fix my issue, but is there any way to run 2 operation in main queue synchronously? – Vahid Jul 30 '18 at 11:45
  • Think about what you're asking: The definition of "synchronous", the singularness of "the main thread", and "2 operations" are fundamentally incompatible. In a word, "No." – ipmcc Jul 30 '18 at 11:47
  • Thank you. I'm involving with a currency crisis in my country. I can't think very well :D – Vahid Jul 30 '18 at 12:04