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:
- startTest called from a button (is IBAction, assuming button tap) on Main thread
- 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).
- You create a new managed object context in the operation, on the Main thread.
- 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).
- 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.