Clicky

iOS Dev Nugget 168 Using Blocks to Manage Contexts

.

Need to run a code review on your codebase? Hire me

Objective-C blocks are very handy. One of the things I like to use it for is to wrap it around a flag that you want to set/reset. For e.g., we often write code like this:

[UIView animateWithDuration:2 animations:^{
    //Do something to views that you want animated

    [UIView setAnimationsEnabled:false];
    //Do something to my views, which I don't want animated
    //More
    //More more
    //More more more
    [UIView setAnimationsEnabled:true];
}];

It's sometimes useful to write a function like this:

- (void)withAnimationsDisabled:(void(^)(void))aBlock {
    [UIView setAnimationsEnabled:NO];
    aBlock();
    [UIView setAnimationsEnabled:YES];
}

You can then modify the first snippet to:

[UIView animateWithDuration:2 animations:^{
    //Do something to views that you want animated

    [self withAnimationsDisabled:^{
        //Do something to my views, which I don't want animated
        //More
        //More more
        //More more more
    }];
}];

This helps make the code read a little better and eliminates the possibility that the flag (setAnimationsEnabled: in this case) is not set to the correct value after your operation is performed. You can use this technique to manage contexts that are more complicated than a single flag: opening and closing of a database connection, opening and closing of a file, creating and releasing some resources (such as CGContext).

The same technique can be used for Swift blocks. It looks better due to Swift syntax:

UIView.animateWithDuration(2) {
    //Do something to views that you want animated

    withAnimationsDisabled {
        //Do something to my views, which I don't want animated
        //More
        //More more
        //More more more
    }
}

Have fun with blocks!


Your feedback is valuable: Do you want more nuggets like this?   Yes   or   No

.

.

Like this and want such iOS dev nuggets to be emailed to you, weekly?

Sign Me Up! or follow @iosdevnuggets on Twitter

.

View archives of past issues