So, as mentioned in this answer and in the iOS 4.0 release notes, UIKit now has some thread-safe drawing facilities:
Drawing to a graphics context in UIKit is now thread-safe. Specifically:
- The routines used to access and manipulate the graphics context can now correctly handle contexts residing on different threads.
- String and image drawing is now thread-safe.
- Using color and font objects in multiple threads is now safe to do.
That's great, but how do you use it?
As far as I'm aware, any time you're not inside -drawRect:
you can only draw using the UIKit/UIGraphics stuff if you've created your own context through UIGraphicsBeginImageContext()
or UIGraphicsPushContext()
, but those functions are not thread safe according to the docs, and -drawRect()
is always called on the main thread.
I assume that creating an image context on the main thread and then starting the background method would be a really bad idea, due to race conditions aplenty.
So, how do I use this multithreaded UIKit-based drawing stuff that was introduced in iOS 4? What other ways of getting an active UIKit graphics context have I missed?
P.S. I know that I could just draw using Core Graphics and be done with it. For various reasons (legacy code) I'd like to continue using the UIKit based drawing methods.
My belief, based on some experience trying it and based on various documents, is that the docs for UIGraphicsPushContext()
are incorrect.
I believe UIGraphicsPushContext()
is in fact thread safe. The particular indication that this is true is QA1637, which says "Beginning with iOS 4.0, drawing to a graphics context in UIKit is thread-safe. This includes accessing and manipulating the current graphics stack, drawing images and strings, and usage of color and font objects from secondary threads." (emphasis mine)
I acknowledge that it is always a dicey proposition to assume thread safety in contradiction to the docs. But I believe this is a documentation error. I have opened rdar://11161530 to track it. Please dupe.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With