title: How do I draw text on a background thread in iOS?
body: <p>I need to draw text on a background thread to save it as an image.</p>
  
  <p>I'm doing</p>
  
  <pre><code>UIGraphicsPushContext()
  [NSString drawInRect:]
  UIGraphicsPopContext()
  </code></pre>
  
  <p>The code works fine, but sometimes it crashes in drawInRect when I'm also drawing on the main thread at the same time.</p>
  
  <p>I tried to use NSAttributedString as suggested here:
  <a href="https://stackoverflow.com/questions/12744558/uistringdrawing-methods-dont-seem-to-be-thread-safe-in-ios-6/12818742#12818742">UIStringDrawing methods don&#39;t seem to be thread safe in iOS 6</a>. But [NSAttributedString drawInRect:] doesn't seem to render anything on my background thread for some reason. Main thread seems to work fine though.</p>
  
  <p>I've been thinking of using Core Text, but looks like Core Text also has similar problem: <a href="https://stackoverflow.com/questions/5642721/coretext-crashes-when-run-in-multiple-threads">CoreText crashes when run in multiple threads</a></p>
  
  <p>Is there a thread safe way to draw text?</p>
  
  <p><strong>UPDATE:</strong>
  If I run this code, it almost immediately crashes in drawInRect with EXC_BAD_ACCESS:</p>
  
  <pre><code>   dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  
        UIGraphicsBeginImageContextWithOptions(CGSizeMake(100, 100), NO, 0);
        UIFont* font = [UIFont systemFontOfSize:14.0f];
  
        for (int i = 0; i &lt; 100000000; i++) {
           [@"hello" drawInRect:CGRectMake(0, 0, 100, 100) withFont:font];
        }
  
        UIGraphicsEndImageContext();
     });
  
     UIGraphicsBeginImageContextWithOptions(CGSizeMake(100, 100), NO, 0);
     UIFont* font = [UIFont systemFontOfSize:12.0f];
  
     for (int i = 0; i &lt; 100000000; i++) {
        [@"hello" drawInRect:CGRectMake(0, 0, 100, 100) withFont:font];
     }
  
     UIGraphicsEndImageContext();
  </code></pre>
  
  <p>If I remove UIFont and just draw text without font it works fine.<br/></p>
  
  <p><strong>UPDATE:</strong>
  This only seems to crash on iOS 6.1, but seems to work fine on iOS 7.1.</p>