Using Blocks in iOS 4: The Basics


Block objects are a C-level syntactic and runtime feature. 

The caret symbol (^) is used as a syntactic marker for blocks.

They are similar to standard C functions, but in addition to executable code they may also contain variable bindings to automatic (stack) or managed (heap) memory. A block can therefore maintain a set of state (data) that it can use to impact behavior when executed.

Blocks are objects that encapsulate a unit of work—or, in less abstract terms, a segment of code—that can be executed at any time.

**blocks are function and can be pass as argument in function**
They are essentially portable and anonymous functions that one can pass in as arguments of methods and functions or that can be returned from methods and functions.


You may also assign a block to a variable and then call it just as you would a function.




  • int (^Multiply)(int, int) = ^(int num1, int num2) {
  •     return num1 * num2;
  • };
  • int result = Multiply(7, 4); // Result is 28.




BLOCK TO Download Image

way 1 ->

UIImage *(^getImage)(NSString *) = ^(NSString *url)
        {
            UIImage *image=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:url]]];

            return image;
        };


imageView.image=getImage(imageURL);


way 2 ->

[self downloadImage_imageURL:YourImageURLString :^(UIImage *image){
        cell.imageView.image=image;
    }]; 
in .h
typedef void (^ myCompletion)(UIImage *image);
-(void) downloadImage_imageURL:(NSString*)url Completion :(myCompletion) completionBlock;
 -(void) downloadImage_imageURL:(NSString*)url Completion :(myCompletion) completionBlock{

    UIImage *image=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:url]]];

    completionBlock(image);
}






Follow Apple's -> A Short Practical Guide to Blocks

Other Tutorial

Part 1
http://pragmaticstudio.com/blog/2010/7/28/ios4-blocks-1

Part 2
http://pragmaticstudio.com/blog/2010/9/15/ios4-blocks-2

Link

http://www.icodeblog.com/2011/08/31/grand-central-dispatch-and-writing-methods-that-accept-blocks-as-arguments/

Comments

Popular posts from this blog

How to Make REST api call in Objective-C.

Launch iPhone simulator without Xcode.

Hacker Rank problem solution