title: How to make NSFilehandle to delete and write data concurrently in Objective c
body: <p>I have written 2 methods:</p>
  
  <ol>
  <li><p>WriteToLogFile</p></li>
  <li><p>DeleteLogFile</p></li>
  </ol>
  
  <p>and I am using <code>NSFileHandle</code> for this</p>
  
  <p>My Code is written as:</p>
  
  <pre><code>- (void)WriteToLogFile:(NSString *)string {
  
   dispatch_async(logQueue ,^ {
          if (nil == fileHandle) {
              // log file not opened
              NSLog(@"LogFile not opened");
              return;
          }
          [fileHandle seekToEndOfFile];
          [fileHandle writeData:[string dataUsingEncoding:NSUTF8StringEncoding]];
        });
      }
  </code></pre>
  
  <p>And other function to delete as:</p>
  
  <pre><code>-(void) deleteLogDataFromFile
  {
      NSString *logFilePath = [self getLogFilePath];
      NSFileManager *fileManager = [NSFileManager defaultManager];
      if([fileManager fileExistsAtPath:logFilePath])
      {
      [[NSFileManager defaultManager] createFileAtPath:logFilePath contents:[NSData data] attributes:nil];
      fileHandle = [NSFileHandle fileHandleForWritingAtPath:logFilePath];
      }
  }
  </code></pre>
  
  <p>Now I am calling these 2 methods  from a loop to check if it crashes at some point where it fileHandle will try to Write to file and will found no such file exist</p>
  
  <pre><code>for (int i = 0; i&lt;1000; i++) {
      [self WriteToLogFile:@"Hello"];
      [self DeleteLogs];
  }
  </code></pre>
  
  <p>And Xcode throws me error b/w loop is running </p>
  
  <blockquote>
    <p>Terminating app due to uncaught exception 'NSFileHandleOperationException', reason: '*** -[NSConcreteFileHandle writeData:]: Bad file descriptor'</p>
  </blockquote>
  
  <p>So I need to know how should I make my Write to file Or Delete to file work together , I know I should do some locking on fileHandle.
  Can anyone tell what should be done in order to fix this  issue?</p>