Three Ways of Threading

Without pretending to completeness or even safety, this section will illustrate three approaches to threading, progressing from worst to best. 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 crunching of numbers 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, a CGContextRef called _bitmapContext. Here’s the structure of MyMandelbrotView’s 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(nil, /* ... */); 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 ...

Get Programming iOS 6, 3rd Edition 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.