views:

388

answers:

2

Apples documentation states that in general Quartz2D is thread-safe. However when drawing to an image context during a NSOperation I'm experiencing crashes (EXC_BAD_ACCESS).

This is my current setup:

UIGraphicsBeginImageContext(imageSize);
CGContextRef context = UIGraphicsGetCurrentContext();
// drawing code
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

I suspect the crashes are related to the current context as the UIGraphicsGetCurrentContext docu states that it needs to be called from the main thread. Is this correct? Are there any other ways to get the image context?

+2  A: 

You've answered your own question. The docs say you have to call UIGraphicsGetCurrentContext() on the main thread, you're not doing so, and your app is crashing. QED.

NSResponder
Thank you for your answer. What would be the correct way to do it? I'm currently looking into CGBitmapContextCreate.
Markus Müller
The correct way to do this would be to break out UIGraphicsGetCurrentContext into a separate call you would run on the main thread, and store the graphics context into a class variable the other thread would make use of on return from the create.
Kendall Helmstetter Gelner
@Kendall-Helmstetter-Gelner That would be an EXTREMELY bad idea. This is not an API designed for use from a background thread at all. Your suggestion leaves open some very gnarly race conditions
Mike Abdullah
Sorry for not getting back to this question sooner. I'm now using CGBitmapContextCreate and it seems to have solved the problem for me. Not sure why I didn't come across this function earlier. Was probably looking for the wrong thing. Thank you everybody for your answers!
Markus Müller
+1  A: 

The various UIGraphics functions are mostly just convenience methods around the lower-level functions. Read up CGGraphicsContext and how to create your own; the documentation is very helpful.

Mike Abdullah