Three Ways of Threading

Without pretending to completeness or even safety, this section will illustrate three approaches to threading. To give the examples a common base, we envision an app that draws the Mandelbrot set. (The actual code, not all of which is shown here, is adapted from a small open source project I downloaded from the Internet.) All it does is draw the basic Mandelbrot set in black and white, but that’s enough number-crunching to introduce a significant delay. The idea is then to see how we can get that delay off the main thread.

The app contains a UIView subclass, MyMandelbrotView, which has one instance variable:

@interface MyMandelbrotView : UIView {
    CGContextRef bitmapContext;
}
// ...
@end

Here’s the structure of its implementation:

// jumping-off point: draw the Mandelbrot set - (void) drawThatPuppy { [self makeBitmapContext: self.bounds.size]; CGPoint center = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds)); [self drawAtCenter: center zoom: 1]; [self setNeedsDisplay]; } // create (and memory manage) instance variable - (void) makeBitmapContext:(CGSize)size { if (self->bitmapContext) CGContextRelease(self->bitmapContext); // ... configure arguments ... CGContextRef context = CGBitmapContextCreate(NULL, /* ... */); self->bitmapContext = context; } // draw pixels of self->bitmapContext - (void) drawAtCenter:(CGPoint)center zoom:(CGFloat)zoom { // .... do stuff to self->bitmapContext } // turn pixels of self->bitmapContext into CGImage, draw into ...

Get Programming iOS 4 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.