title: dispatch_sync vs. dispatch_async on main queue
body: <p>Bear with me, this is going to take some explaining. I have a function that looks like the one below.</p>
  
  <p>Context: "aProject" is a Core Data entity named LPProject with an array named 'memberFiles' that contains instances of another Core Data entity called LPFile. Each LPFile represents a file on disk and what we want to do is open each of those files and parse its text, looking for @import statements that point to OTHER files. If we find @import statements, we want to locate the file they point to and then 'link' that file to this one by adding a relationship to the core data entity that represents the first file. Since all of that can take some time on large files, we'll do it off the main thread using GCD.</p>
  
  <pre><code>- (void) establishImportLinksForFilesInProject:(LPProject *)aProject {
      dispatch_queue_t taskQ = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
       for (LPFile *fileToCheck in aProject.memberFiles) {
           if (//Some condition is met) {
              dispatch_async(taskQ, ^{
                  // Here, we do the scanning for @import statements. 
                  // When we find a valid one, we put the whole path to the imported file into an array called 'verifiedImports'. 
  
                  // go back to the main thread and update the model (Core Data is not thread-safe.)
                  dispatch_sync(dispatch_get_main_queue(), ^{
  
                      NSLog(@"Got to main thread.");
  
                      for (NSString *import in verifiedImports) {  
                              // Add the relationship to Core Data LPFile entity.
                      }
                  });//end block
              });//end block
          }
      }
  }
  </code></pre>
  
  <p>Now, here's where things get weird:</p>
  
  <p>This code works, but I'm seeing an odd problem. If I run it on an LPProject that has a few files (about 20), it runs perfectly. However, if I run it on an LPProject that has more files (say, 60-70), it does <strong>NOT</strong> run correctly. We never get back to the main thread, the <code>NSLog(@"got to main thread");</code> never appears and the app hangs. BUT, (and this is where things get REALLY weird) --- if I run the code on the small project FIRST and THEN run it on the large project, everything works perfectly. It's ONLY when I run the code on the large project first that the trouble shows up.</p>
  
  <p>And here's the kicker, if I change the second dispatch line to this:</p>
  
  <pre><code>dispatch_async(dispatch_get_main_queue(), ^{
  </code></pre>
  
  <p>(That is, use <code>async</code> instead of <code>sync</code> to dispatch the block to the main queue), everything works all the time. Perfectly. Regardless of the number of files in a project! </p>
  
  <p>I'm at a loss to explain this behavior. Any help or tips on what to test next would be appreciated. </p>