Skip to content
This repository has been archived by the owner on Jun 2, 2018. It is now read-only.

Why not return to the main thread after constructing a stack ? #123

Closed
plm75 opened this issue Apr 19, 2016 · 6 comments
Closed

Why not return to the main thread after constructing a stack ? #123

plm75 opened this issue Apr 19, 2016 · 6 comments

Comments

@plm75
Copy link

plm75 commented Apr 19, 2016

It is pretty common inside a TableViewController's init or viewDidLoad method to have initialisation code like the following:

override func viewDidLoad() {
  super.viewDidLoad()
  CoreDataStack.constructSQLiteStack(withModelName: "SomeName") { outcome in
    print(NSThread.isMainThread())     // false
    switch outcome {
      case .Failure(let error)        : print(error)
      case .Success(let coreDataStack):
        self.coreDataStack = coreDataStack
        self.tableView.reloadData()    // crash
    }
  }  
}

This code will crash however because the callback is executed on a background thread (created by setupSQLiteBackedCoordinator.

Unless I missed something, it seems to me it would be less confusing if the callback was executed on the main thread. After all, once the stack has been set up why remain in the background thread?

A pretty simple fix would be to just wrap the callback calls inside constructSQLiteStack:

    dispatch_async(dispatch_get_main_queue(), { 
      callback(.Success(stack))  // or callback(.Failure(error))
    })
@rcedwards
Copy link
Contributor

While in many cases you may want to work with your Stack on the main thread after setup, this is not a universal situation.

I do think we could simplify the setup by including a parameter to specify the callback queue similar to how NSURLSession's delegateQueue works. Perhaps this could default to the main queue, but I'm not sure about that yet.

@rcedwards
Copy link
Contributor

@zwaldowski curious about your opinion on this one also.

@zwaldowski
Copy link
Contributor

Providing a queue would be fine but I think pushing to the main thread is an API design crutch.

@rcedwards
Copy link
Contributor

CoreDataStack API design crutch or app level API design crutch?

@zwaldowski
Copy link
Contributor

Er, both.

@rcedwards
Copy link
Contributor

Added in v1.2.4

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants