3
What is the difference between blocks and functions in Objective-C?
3
What is the difference between blocks and functions in Objective-C?
7
The block is an "anonymous function", which you assign to a variable and/or pass on as parameter. Since the function has no name, you can only use it if you have a direct reference.
Example taken from Apple documentation: (https://developer.apple.com/library/ios/documentation/cocoa/Conceptual/Blocks/Articles/bxGettingStarted.html#//apple_ref/doc/uid/TP40007502-CH7-SW1)
int (^myBlock)(int) = ^(int num) {
return num * multiplier;
};
The block is similar to the Ruby code block, the Javascript Function(), it is also similar to the closure present in many languages, but with limitations.
The block is interesting when you have to callback Cocoa. Often this callback is short, and it is bureaucratic to create another method or function just to pass it on.
Quite common situation in animations. Example taken from https://stackoverflow.com/questions/12292044/putting-a-fade-in-fadeout-effect-on-objective-c
[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();
}];
}];
Browser other questions tagged objective-c
You are not signed in. Login or sign up in order to post.