title: NSFileHandle writeData synchronously delaying main thread operations
body: <p>I have a custom implementation of a logger, which logs the actions and operations in my app.</p>
  
  <p>A strong <code>NSString</code> reference is living in one of my Singleton Classes.</p>
  
  <p>I call a method named "<code>-(void)writeToFile: (BOOL) rightNow</code>", whenever I need to log something. This method also lives in that Singleton class.</p>
  
  <p>Yes passed to <code>rightNow</code>, will trigger the immediate call to <code>writeData:</code> on NSFileHandle, forcing the NSString to be written to the file and emptying the NSString afterwards.</p>
  
  <p>No, will only append the string and wait for a <code>Yes</code> value in <code>rightNow</code> to do the write operation.</p>
  
  <p>Whenever I call <code>writeToFile</code> from a method which is being called through a timer, with <code>rightNow</code> param as <code>YES</code>, my app halts for 5/6 mins.</p>
  
  <p>Similarly, If I call <code>writeToFile</code> from a block (let's say a web service returned some data on a block), the app halts again.</p>
  
  <p>To my understanding, since <code>writeData</code> works synchronously, for some reason, it breaks when called from block or timers (which I am assuming are called on different threads).</p>
  
  <p>Is this the expected behavior? I could wrap my <code>writeToFile</code> call around GCD, but what if the thread I am requesting (main/global), the current state is that only? Wouldn't it create a deadlock calling main thread on main thread?</p>
  
  <p>Code:</p>
  
  <pre><code>- (void) writeToFile: (NSString *) targetString rightNow: (BOOL) rightNow
  {
      //_loggingString holds the data, which keeps on accumulating as the user performs operations. At some point of time (callbacks from API's I call this method, to actually, write this string in the file and clear this string afterwards.)
      NSString *oldString = [_loggingString copy];
  
      _loggingString = [oldString stringByAppendingString:targetString];
  
      if (rightNow)
      {
          if (![[NSFileManager defaultManager]fileExistsAtPath:@"somePath"])
          {
              [[NSFileManager defaultManager]createFileAtPath:@"somePath" contents:nil attributes:nil];
          }
  
          NSFileHandle *fileHandle =  [NSFileHandle fileHandleForWritingAtPath:@"somePath"];
  
          [fileHandle seekToEndOfFile];
  
          [fileHandle writeData:[_loggingString dataUsingEncoding:NSUTF8StringEncoding]];
  
          _loggingString = @"";
      }
  }
  </code></pre>