How To Use Blocks in Objective-C Programming

Objective-C blocks are C-level constructs code much like inline functions, anonymous functions, clojures or lambdas in other programming languages. They can also be viewed as function pointers but their design is cleaner and more elegant. Blocks were added to the Mac OSX 10.6 and iOS 4 SDKs to process a set of instructions, like a function, without requiring a separate function. Blocks makes code more readable and easier to maintain. Like functions, Blocks can have a return value and can have parameters or simply have a void return type.

General Syntax


The general syntax of a block starts with a caret (^) followed either by a set of curly braces containing a block of code or a set of parameters, enclosed in parentheses, with or without a return value. Here are some examples

^{ printf("Hello World!"); }

or

^{ NSLog(@"Hello world!"); }

In the above simple examples, you can see that the caret replaces the function name. You can embed this bit of code within an existing Objective-C method like the following snippet demonstrates:

-(void) someMethod{

   ^{
	NSLog(@"Hello world!");
    }

}

Naturally this is a bit mundane as it would be simpler just to add the NSLog code directly to the method, but this code helps illustrate the usage pattern of Blocks.

Another form of blocks involves using parameters or arguments as the following examples shows:

^(float a, float b, NSString *ops){
	float result = 0.0;

switch(ops)
{
	case "/":
result = a / b;
	break;
	case "*":
result = a * b;
	break;
	case "+":
result = a + b;
	break;
	case "-":
result = a - b;
	break;
}
	
return result ;
}

This “block” of code takes three arguments, one for two possible numbers and the third to allow for a arithmetic operation. To use this type of block, you could assign it to a float block signature or to a variable which is known as a Block Variable.

The following code demonstrates the former:

float(^ floaterDiv)(float, float, string) = ^(float a, float b, NSString *ops){
	float result = 0.0;

switch(ops)
{
	case "/":
result = a / b;
	break;
	case "*":
result = a * b;
	break;
	case "+":
result = a + b;
	break;
	case "-":
result = a - b;
	break;
}
	
return result ;
}

Declaring Block Variables


Blocks like functions can either have no return value, hence have a void return type or either a primitive data type or an Objective-C data type. The following code snippet demonstrates how to declare and define the block variable code.

 float (^ floatOp)(float, float, int);
    
	
    floatOp  =  ^(float a, float b, int ops){
        float result=0.0f;
        
        switch (ops) {
            case 1:
                result = a/b;
                break;
                
            default:
                break;
        }
        return result;
    };
    
    
    float mathOp = floatOp(4.0f, 5.0f, 1);
    
    NSLog(@"%f", mathOp);

You would need to first declare the variable and any arguments types, if any as the following code snippets shows:

float (^ floatOp)(float, float, int);

This block variable declaration has a return value of float, next the variable name, floatOp, is defined by preceding the name with a caret, ^, and enclosing the name in parentheses. Then the variable’s arguments types, also enclosed in parentheses, are defined.

Once the Block Variable’s signature is declared, you can next add the logic to its body which encapsulated in curly braces as the following code demonstrates:

floatOp = ^(float a, float b, int ops){
float result=0.0f;

switch (ops) {
case 1:
result = a/b;
break;

default:
break;
}
return result;
};

Here the floatOp variable is assigned the signature of ^(float a, float b, int ops) which also include actual arguments. The body is then enclosed in curly braces and resembles the body of any standard C function or Objective-C method. Notice also that the block code is terminated by a semi-colon like any other expression.

Using Typedef


If you prefer, you can use the typedef keywork to declare the block variable in the header or outside the implementation body of class as the following code shows:

#import <UIKit/UIKit.h>

typedef void(^ replaceString)(NSString*, NSString*, NSString* );
@interface klViewController : UIViewController

@end

A block variable, replaceString, with a void return type is declared with a signature of three NSString variables. Of course we could have placed the code in the implementation file as follows:

#import "klViewController.h"

typedef void(^ replaceString)(NSString*, NSString*, NSString* );

@interface klViewController ()

@end

@implementation klViewController
â¦

The result is the same unless of course you want the block variable to have a public scope; to make visible outside the class, then you would declare the block variable in the header.

Scope of a Block


All Blocks are created on the stack like other primitive types and will be destroyed when the enclosing function or method goes out of focus or from the stack frame. To persist the Block after the enclosing method is released, you can use the copy function to move the Bock from the stack to the heap as the following example demonstrates:

SomeObject objInstance = [floatOp copy];

In Summary


Blocks can be confusing at first but offer an elegant solution in event driven apps. They offer performance gains by providing a way to process a block of code on the stack within an existing method or function.

More by this Author


Comments 4 comments

rajkishor09 profile image

rajkishor09 4 years ago from Bangalore, Karnataka, INDIA

great work,i found one buddy who is programmer ;)


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

Hey thanks, I really appreciate your feedback.


vv 4 years ago

Great Article......


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

Thanks

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Click to Rate This Article
    working