Colorize on iOS 5


#1

I’m wondering if there is something that changed with Blocks in iOS 5. Long story, but I had gone through the book using Xcode 4.0 and iOS 4.3 and am now going through with iOS 5 and Xcode 4.2. On page 393 I’ve implemented the code to send the message colorize when shaken, but it doesn’t seem to work. Below is my code that has been added to TouchDrawView.m. Have I missed something?

- (void)transformLineColorsWithBlock:(UIColor * (^)(Line *))colorForLine
{
    for(Line *l in completeLines) {
        UIColor *c = colorForLine(l);
        [l setColor:c];
    }
    [self setNeedsDisplay];
}

- (void)colorize
{
    // Vertical means more red, horizontal means more green
    // longer means more blue
    
    // A block variable named colorScheme is created here:
    UIColor * (^colorScheme)(Line *) = ^(Line *l) {
        // Compute delta between begin and end points
        // for each component
        float dx = [l end].x - [l begin].x;
        float dy = [l end].y - [l begin].y;
        
        // If dx is near zero, red = 1, otherwise, use slope
        float r = (fabs(dx) < 0.001 ? 1.0 : fabs(dy / dx));
        
        // If dy is near zero, green = 1, otherwise, use inv. slope
        float g = (fabs(dy) < 0.001 ? 1.0 : fabs(dx / dy));
        
        // blue = length over 300
        float b = hypot(dx, dy) / 300.0;
        
        return [UIColor colorWithRed:r green:g blue:b alpha:1];
    };
    
    // Pass this colorScheme block to the method
    // that will iterate over every line and assign
    // the computed color to that line
    [self transformLineColorsWithBlock:colorScheme];
}

- (BOOL)canBecomeFirstResponder
{
    return YES;
}
- (void)didMoveToWindow
{
    [self becomeFirstResponder];
}
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    [self colorize];
}

#2

Looks like it should work. Put NSLogs in all of those methods to make sure they are being called.