Why is my app crashing when I modify a Core Data relationship in an NSOperation subclass? Why is my app crashing when I modify a Core Data relationship in an NSOperation subclass? multithreading multithreading

Why is my app crashing when I modify a Core Data relationship in an NSOperation subclass?


You are crossing the streams (threads in this case) which is very bad in CoreData. Look at it this way:

  1. startTest called from a button (is IBAction, assuming button tap) on Main thread
  2. Your for loop creates a JGMakeRelationship object using the initializer trainGroup: withProject: (this should be called init, and probably call super, but that's not causing this issue).
  3. You create a new managed object context in the operation, on the Main thread.
  4. Now the operation queue calls the operations "main" method from a worker thread (put a breakpoint here and you'll see it's not on the main thread).
  5. Your app goes boom because you've accessed a Managed object Context from a different thread than the one you created it on.

Solution:

Initialize the managed object context in the main method of the operation.