Friday 1 March 2013

BLocks in Objective -C


About Blocks

Blocks are a new feature that was introduced in iOS 4.0 and Mac OSX 10.6. Blocks can greatly simplify code. They can help you reduce code, reduce dependency on delegates, and write cleaner, more readable code.

What is block?


A Block is a Nothing but Chunk of Code, and also say that Objective -C Objects.They can pass as the parameters over a method.
ex:
int (^add)(int,int) = ^(int number1, int number2){
                            return number1+number2;
}

int resultFromBlock = add(2,2);

 calling a block(add) and assign the result to variable

When we ll use Blocks?


Blocks are particularly useful as a callback because the block carries both the code to be executed on callback and the data needed during that execution.

Animating a view WithOut Using Blocks



- (void)removeAnimationView:(id)sender {
    [animatingView removeFromSuperview];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    [UIView beginAnimations:@"Example" context:nil];
    [UIView setAnimationDuration:5.0];
    [UIView setAnimationDidStopSelector:@selector(removeAnimationView)];
    [animatingView setAlpha:0];
    [animatingView setCenter:CGPointMake(animatingView.center.x+50.0,
                                         animatingView.center.y+50.0)];
    [UIView commitAnimations];
}

Animating a view With Using Blocks


- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    [UIView animateWithDuration:5.0
                     animations:^{
                        [animatingView setAlpha:0];
                        [animatingView setCenter:CGPointMake(animatingView.center.x+50.0,
                                                             animatingView.center.y+50.0)];
                     }
                     completion:^(BOOL finished) {
                         [animatingView removeFromSuperview];
                     }];

Comparison among  with blocks and without Blocks:


With blocks, we don’t have to do things like declare an entirely separate method for completion callback, or call the beginAnimations/commitAnimations line.

Final conclusion:


Blocks can reduce the Code, and reduce dependency on delegates.


Source From: RaywenderLich Site

No comments:

Post a Comment