Drawing in a background thread on iOS

Jon Tirsen picture Jon Tirsen · Oct 9, 2011 · Viewed 8.4k times · Source

I have a view with some very complex drawing logic (it's a map view that draws from GIS data). Doing this drawing on the main thread locks up the UI and makes the app unresponsive. I want to move away the drawing to a background thread with for example an NSOperation.

What is the best way to structure this?

I am currently drawing to an off memory CGContext and then convert that to a CGImageRef which I send to the view to blit on the main thread. Unfortunately this uses up a lot of memory and it seems that the GPU acceleration is no longer used as it is quite a bit slower. Is there some way of drawing directly to the view from a background thread? I know that UIKit isn't multi-thread safe but maybe there is some way of locking the view while I'm doing the drawing?

Answer

Dan Rosenstark picture Dan Rosenstark · Oct 11, 2011

Beyond iOS 4.0, drawing is thread safe. You might need to create a CGContext yourself, but there is no reason you cannot draw on a background thread.

That said, most UIKit operations are not. If you need to do those, you can always prepare in a background thread, and then use performOnMainThread when needed. There's even waitUntilDone. That said, you should use NSOperation and NSOperationQueue, apparently.