Functional and Asynchronous Programming in iOS

A couple of months ago I started working on a simple project using node.js and I wanted to write a post about the similarities and differences in functional programming between JavaScript and Objective-C. However, while I was writing that post I realized I did not truly understand functional programming. I could write blocks in Objective-C and I could write functions in JavaScript but the theory behind it was lost to me. That being said, I decided to dig deeper to understand not just what the code was accomplishing but why.

“Functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data.” -- Wikipedia

Functional Programming

Considering my background as an iOS developer, I’ll start with blocks. “A block is a section of code which is grouped together” -- Wikipedia. In Objective-C, blocks are used to package up code allowing it to be called in any function on any thread. This is made possible using closures, which saves the state of the variables contained within the block for proper execution elsewhere. “Blocks are particular useful as a callback because the block carries both the code to be executed on callback and the data needed during that execution” -- Apple. One example of this would be the new way of animating UIView transitions:

[UIView animateWithDuration:0.5
            self.view.transform =
                CGAffineTransformMakeTranslation(132.0, 0.0);
        completion:^(BOOL finished) {
            self.view.backgoundColor = [UIColor blackColor];

In this method, two blocks are passed in as parameters to execute at specific times. Doing it this way is much cleaner than the previous way of animating:

- (void)performAnimations {
    [UIView beginAnimations:@"animation" context:NULL];
    [UIView setAnimationDuration:0.5];

    self.view.transform = CGAffineTransformMakeTranslation(132.0, 0.0);

    [UIView commitAnimations];

    [self performSelector:@selector(performCompletion)

- (void)performCompletion {
    self.view.backgoundColor = [UIColor blackColor];

As you can see, it is much cleaner now using blocks as opposed to needing to set two methods and a delay to accomplish the same thing. Apple made it simple to pass the animation method: a function for the animations to perform, and a function for what to change upon completion. Blocks also do quite a bit for asynchronous programming in Objective-C as well, but we’ll get into that later.

Now moving on to functional programming in JavaScript. “JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions.” -- Wikipedia It is a language used primarily for web development, both server side and client side. The three key functional components that JavaScript makes use of are first-class functions, nested functions, and closures. First-class functions are treated like variables, they can be passed as arguments, altered, and executed elsewhere in the code. Nested functions are defined inside of a function and are able to retain and use variables from the parent function. Closures, much like in Objective-C, saves the data located within a function so that it can be executed elsewhere while containing the current values of the variables.

var getValue1 = function (callback) {
    var value1 = 20;

var getValue2 = function (callback) {
    var value2 = 30;

var displayTotal = function () {
    var total;
    getValue1(function(value1) {
        getValue2(function(value2) {
            function getTotal() {
                total = function() {
                    return (value1 + value2);


In this example, the displayTotal function makes use of first-class functions and nested functions, and closures. Within that function, it calls getValue1 uses getValue2 as a callback, which in turn uses getTotal as a closure. This string of functions trickles the necessary information down to the final function that simply displays the total in the console. Nested functions play a big role when doing more complicated work where you need to make a comparison between two objects where you need to first pull down the two objects based on a unique id that is sent to the method.

While both Objective-C and JavaScript use closures and functions as callbacks, they are very different in how they do it. Thanks to first-call functions, JavaScript is able to easily pass a function around from function to function as a variable and execute it at any time. Objective-C, on the other hand, can pass a block to a selector and use that as a callback but is unable to pass a block to a block as a variable.

Asynchronous Programming

As of iOS4, blocks were released into the iPhone world opening up a much cleaner and more efficient way of asynchronously programming. Previously, you needed to use both NSThread and NSOperationQueue in order to queue up and run methods in a background thread:

- (void)callSelectorInBackgroundQueue:(SEL)selector {
    NSOperationQueue *queue = [NSOperationQueue new];
    NSInvocationOperation *operation =
        [[NSInvocationOperation alloc] initWithTarget:self
    [queue addOperation:operation];
    [operation release];
    [queue release];

- (void)getObjects {
    [NSThread detachNewThreadSelector:@selector(launchExecution) toTarget:self withObject:nil];

- (void)getObjectsFromServer {
    // make a call to get objects from the server

So making an asynchronous call in a queue would require allocating memory to three different objects to be accomplished pre-iOS4. With the introduction of Grand Central Dispatch (GCD) alongside of blocks, Apple brought a better way to manage background threads while queueing up operations:

+ (void)makeCallInBackgroundForBlock:(void (^)(void))block {
    dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

Simply put, it is much cleaner code and requires very few explicit memory allocations. The use of blocks in Objective-C has added to the codes readability and efficiency. It is clear that blocks primarily for closures. Being an object oriented language, there are limits to what functionality Objective-C can implement from a functional language standpoint. That being said, it takes advantage of what it can and does a good job of making it work for the developer.