ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

How To Use Blocks in Objective-C Programming

Updated on September 23, 2012

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.

Comments

    0 of 8192 characters used
    Post Comment

    • klanguedoc profile imageAUTHOR

      Kevin Languedoc 

      6 years ago from Canada

      Thanks

    • profile image

      vv 

      6 years ago

      Great Article......

    • klanguedoc profile imageAUTHOR

      Kevin Languedoc 

      6 years ago from Canada

      Hey thanks, I really appreciate your feedback.

    • rajkishor09 profile image

      RAJKISHOR SAHU 

      6 years ago from Bangalore, Karnataka, INDIA

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

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)