Objective-C Quickie – Block variables

Blocks are becoming more and more preferred in iOS and Objective-c, with most of the UIView animations becoming block based and methods added to the NS collection classes to use blocks for enumeration. Blocks can also be stored as variables and used over and over again. This is immensely useful when subscribing to a DRY method of coding.

Below is some code I’m using to apply transformations to CALayers. I’ve got three sets of them, and since I simply want to apply the same transformation to them, I can write the block for creating and applying the transformation once, and use it on all three sets:

// this is a block variable
id transBlock = ^(id obj, BOOL *stop)
{
    CALayer *layer = (CALayer *)obj;
    CGAffineTransform trans = CGAffineTransformConcat([layer affineTransform],                                                       CGAffineTransformMakeTranslation(delta * 0.7, 0));
    [layer setAffineTransform:trans];
};

[displayedBars enumerateObjectsUsingBlock:transBlock];
[displayedBarLabels enumerateObjectsUsingBlock:transBlock];
[displayedAxisLabels enumerateObjectsUsingBlock:transBlock];

Advertisements

Posted on April 5, 2011, in Code and tagged , , , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: