tags:

views:

105

answers:

2

I understand that to use the UIActivityIndicator you must start it in the main thread, and then do your long running operation on a background thread. I also understand that all UIKit operations should be done on the main thread as well.

But what I am faced with now is a long running operation to create CALayers using the Quartz CGContext drawing methods, and I'm wondering if it is possible to do the Quartz stuff in a background thread so I can display a activity indicator while my complex graphs are being drawn?

I'm pretty new to Quartz and have to admit I get lost easily in this area. I'm hoping that it is different enough from UIKit to allow background context drawing operations.

A: 

You don't create CALayers using the Quartz CGContext drawing methods. You draw into CALayers using the CGContext drawing methods. This happens during the drawing phase of the run loop when it calls drawInContext:, and you don't have control over what thread that happens on (or even when it happens really). You want to keep those as quick as possible, so for complex layers you should as much pre-calculation as you can and save off the answers, paths, etc.

I feel you may mean something else though. What do you mean by "create CALayers?"

Rob Napier
Yeah, I chose the words poorly there. I've already got all the layers and the Quartz drawing into the CGContexts working (there are several off them as they are lined up in a UIScrollView). The problem is it takes up to 5 seconds or more to complete drawLayer:inContext: method and I would like to have an activity indicator spinning during those 5 seconds.I was hoping I could start the activity indicator in the main thread, then fire a background process that draws into the CGContexts. I guess my question is really a Quartz question. Can you work with a CGContext in a background thread?
Dav
+2  A: 

Spin off an NSThread and draw into a context you've created via CGBitmapContextCreate. When it's complete, use -[NSObject performSelectorOnMainThread:withObject:waitUntilDone:] to send the image you get from CGBitmapContextCreateImage back to the main thread to be assigned to a CALayer's contents property. Be sure that your drawing code is thread-safe.

rpetrich
+1 This is the kind of approach you want. -drawLayer:inContext: *cannot* run for 5 seconds. You don't control when it runs, and it may run many times. Do the work somewhere else, then apply it to the layer.
Rob Napier