title: Core Data & GCD: Passing the correct managed object context to custom NSManagedObjects
body: <p>I get runtime errors which seem to result from my incorrect implementation of <code>GCD</code> in combination with my custom NSManagedObjects.</p>
  
  <p>Nested in a <code>GCD</code> call, I am using custom NSManagedObjects which (seem to) have their own managed object contexts (= <code>self.managedObjectContext</code>). </p>
  
  <p>I am creating the managed object context in the app delegate by using the managed object context provided by <code>UIManagedDocument</code>: <code>self.managedDocument.managedObjectContext</code>.</p>
  
  <p>I don't understand how to pass the correct managed object context down to my custom NSManagedObjects. How would I need to change my code to use the correct managed object context?</p>
  
  <p>This is my main method (inside a view controller):</p>
  
  <pre><code>dispatch_queue_t queue;
  queue = dispatch_queue_create("queue", NULL);
  dispatch_async(queue, ^{
  // ...
  NSDecimalNumber *value = [reportedPeriod 
     valueForCoa:figure.code 
     convertedTo:self.currencySymbol];
  // ...});
  }
  </code></pre>
  
  <p>In this main method I do not have any reference to a managed object context, I do just call <code>valueForCoa:convertedTo:</code> (which is coded as follows):</p>
  
  <pre><code>- (NSDecimalNumber*)valueForCoa:(NSString*)coaStr
  convertedTo:(NSString*)targetCurrencyStr {
  // ...
  CoaMap *coa = [CoaMap coaItemForString:coaStr
     inManagedObjectContext:self.managedObjectContext];
  // ...
  }
  </code></pre>
  
  <p><code>valueForCoa</code> is a method in my custom subclassed NSManagedObject <code>ReportedPeriod</code> and uses its (default) managed object context <code>self.managedObjectContext</code>.</p>
  
  <p>The app then usually crashes in the custom subclassed NSManagedObject <code>CoaMap</code> in the following method when it executes the fetch request:</p>
  
  <pre><code>+ (CoaMap*)coaItemForString:(NSString*)coaStr 
  inManagedObjectContext:(NSManagedObjectContext*)context {
  
  NSFetchRequest *request = [NSFetchRequest 
  fetchRequestWithEntityName:NSStringFromClass([self class])];
  NSPredicate *predicate = 
     [NSPredicate predicateWithFormat:@"coa == %@",coaStr];
     request.predicate = predicate;
  // ** The runtime error occurs in the following line **
  NSArray *results = [context executeFetchRequest:request error:nil];
  // ...
  }
  </code></pre>
  
  <p>The error message is: <code>Terminating app due to uncaught exception 'NSGenericException', reason: '*** Collection &lt;__NSCFSet: 0x9a8a4a0&gt; was mutated while being enumerated.</code></p>
  
  <p>Could you please help me with this issue and give me some suggestions on how to improve my code to pass the correct managed object contexts (or on how to make sure that the correct context is used in all methods)?</p>
  
  <p>Thank you very much!</p>