O'Reilly logo

Programming iOS 4 by Matt Neuburg

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required