Blocks vs. Functions in Objective-C

3

What is the difference between blocks and functions in Objective-C?

    
asked by anonymous 13.02.2014 / 03:59

1 answer

7

The block is an "anonymous function," which you assign to a variable and / or pass on as a parameter. Since the function has no name, it can only be used by someone who has a direct reference.

Example taken from the Apple documentation: ( link )

int (^myBlock)(int) = ^(int num) {
    return num * multiplier;
};

The block is similar to Ruby's code block, to Javascript's function (), and is similar to closure present in many languages, but with limitations.

The block is interesting when you need to pass a callback to Cocoa. Many times this callback is short, and it is bureaucratic to create another method or function just to pass it on.

Situation quite common in animations. Example taken from link

 [UIView animateWithDuration:0.5f animations:^{
        // fade out effect
        _self.myView.alpha = 0.0f;
    } completion:^(BOOL success){
        [UIView animateWithDuration:0.5f animations:^{
            // fade in effect
            _self.myView.alpha = 1.0f;
        } completion:^(BOOL success){
            // recursively fire a new animation
            if (_self.fadeInOutBlock)
                _self.fadeInOutBlock();
        }];
    }];
    
13.02.2014 / 04:17