8 May 2014 1min read

Using blocks to simplify

The use of blocks has spread over all Objective-C code. Normally we see them as callbacks (completion blocks) for animations or for async tasks (GCD, another cool kid) but they can be used to a lot more.

For example we all know the -[NSArray enumerateObjectsUsingBlock:] method. It allow us to perform some code for each object in an NSArray.

Of course, there are a lot of other scenarios for using blocks, but today I want to share with you one scenario where the use of blocks can solve the problem in a nice way.

The scenario

You can use blocks to perform some arbitrary code just under some conditions without the need to repeat the code to check those conditions and even without having direct pointers to the needed objects.

Example:

- (void)modifyViewWithBlock:(void(^)(CustomView *view))block {
    // Check some conditions
    if ( ....) {
        // Lookup the correct view 
        // assign a property, a switch case, search in the view hierarchy, etc...
        UIView *view = ... 

        // Common things
        // Animation block, send notifications...
        ...
        block(view);
        ...
    }
}

Usage:

// User taps button A
[self modifyViewWithBlock:^(CustomView *view){
    set the background color to red
    change the size to 20x20
    change the position to 0,0
    ... other custom changes
}];

// User taps button B
[self modifyViewWithBlock:^(CustomView *view){
    just set the background color to blue
}];

// Some notification arrives
[self modifyViewWithBlock:^(CustomView *view){
    custom changes
}];

With these approach:

  • No need to have the objects that you need.
  • Execute the changes only if a condition is met.
  • The changes can be different depending on some other conditions.
  • Allows to perform common code easily.

I really like these approach because there are less repeated code (the lookup, the conditions check, the common things...) and I can focus on writing the block, like the enumerateObjectsUsingBlock allows us to write our code without thinking about the enumeration at all.

If you enjoyed this post

Continue reading