completion:^{ … ;}

 

As an appetizer, here are some slides from a presentation I made. Trying to explain this “obscure” feature called closures, that pretty much all the best programming languages have… _blocks!

 

 


Having fun with blocks?

All right then, let’s start with a sample app. We will simply fetch an image from the internet, given some url, and then display the image to the user.

 

 

 

In the image below, you can see how we can initially use blocks with Grand Central Dispatch (GCD), to schedule a task – or an execution block of code, in other words – on a background thread and then back on the main thread to update our UI.

 

Screen Shot 2016-03-07 at 7.03.40 AM

 

 

Now, to clean up our code a little bit, let’s refactor the code into some “fetchImage” method. Now we could literally copy and paste the outer dispatch_async function call, passing just the url, as a parameter, to fetch and display the image. Although, in order to write more general and reusable code, we should try to keep separate the two main things our method is doing. 1) Request an image over the internet, for a given url. And 2) Do something with that image.
The chosen way to do it relies again on the usage of blocks.

 

Screen Shot 2016-03-07 at 7.22.20 AM

 

Declaring our method like:

 - (void)fetchImageWithURL:(NSURL *)url completionBlock:(void(^)(UIImage *))completionBlock;

Will allow us to pass some code (a block / closure), as an argument, when we call this method inside the loadWallpaper implementation, to display the image.

 

Screen Shot 2016-03-07 at 7.31.49 AM

 

 


 

 

Using typedef to redefine the block object (compound) type.

It can be really annoying to deal with the block’s syntax, especially when it comes to defining methods with block type parameters.
The best practice to cope with this is to extract the block type in a typedef and to use the redefined type in our method definitions, resulting in a much much cleaner and more readable code.

typedef void (^ImageCompletionBlock)(UIImage *);
- (void)fetchImageWithURL:(NSURL *)url completionBlock:(ImageCompletionBlock *))completionBlock;

 

 

At this point you might be thinking a pair of things. One probably is that you are starting to realize how powerful blocks are and how mastering your closure kung-fu can leverager your skill set as a developer. And the other one? Well, most likely you are also thinking something like… F**king bocks syntax! But don’t worry you are not alone! The syntax it what it is, no questions. But besides that it’s really worth to use blocks.


 

 

So, back to your app. As you can see from the above image we might want to resize our image before we display it to the user. In this way we can employ the same pattern, we used so far, to take advantage of functional programming with blocks. Once we declare a method in order to resize the image,

- (void)resizeImage:(UIImage *)image toWidth:(CGFloat)width complitionBlock:(ImageComplitionBlock)complition;

we can just call this method from the fetchImageWithURL:complitionBlock: implementation and then simply pass the complitionBlock parameter forward to the inner method call.

 

Screen Shot 2016-03-07 at 10.24.20 PM

 

 

Now, to wrap up our sample application, and keep playing with blocks one more time, let’s add some animations to the imaged. As soon as the activity indicator starts spinning, we want the current displayed image to fade out. When the new image is ready to be displayed and the indicator stops spinning, we want to fade back in the new image. In order to obtain that effect, we will add two calls to

 [UIView animateWithDuration: (NSTimeInterval)duration animations: ^(void)animations];

inside the loadWallpaper method’s implementation. Then, as animation block we’ll just set the alpha property, for the imageView. First to 0, to fade out the old imageAnd then back to 1, to fade in the new one.

 

Screen Shot 2016-03-07 at 10.52.03 PM

 

Lastly, we would like to implement and call a bounceImage method, which will again animate the transform property of our image. This will give our app a quite neat effect and will catch the user attention as soon as a new image is displayed.

 

Screen Shot 2016-03-07 at 10.48.50 PM

 

Even though we could consider ourselves very satisfied with our unique and awesome sample app, there’s still one more step we can go ahead, to make this last bounceImage method much more readable. Once again, the solution relies on using blocks.

Let’s define another typedef. In this case, the compound block type will still have no return value, as before, but no parameters.

typedef void (^ActionBlock)();

 

 

And at this point we can refactor the code in a better way, using a scaleImage:completion: method which will take a (CGFloat) scale and an (ActionBlock) completion block parameter.

Screen Shot 2016-03-07 at 8.06.15 AM

 

 

 

*For further details, regarding the sources of this post, please refer to this video session from NSScreenCast.

**You may also like to read further on what to watch out for, when programming with blocks.