Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between methods and blocks in Objective-C

I am relatively new to programming and there is one thing which I can not manage to wrap my hand around. That is, what are blocks and why/when would you use them? What is the difference between a block and a method? To me, they seem like they kind of do the same thing.

Can some explain this to me?

Yes, I did spend hours on Google before finally coming here to ask.

like image 748
Balázs Vincze Avatar asked Jan 07 '23 04:01

Balázs Vincze


2 Answers

  • Blocks are the anonymous function.
  • Blocks are used to executed at a later time but not the function can be used to execute later.
  • Blocks are commonly used for call back (No need to use delegates)
  • Blocks are objects but functions are not objects.

Suppose you want to perform an operation like the animation on view and wanted to be notified after completion. Then you had to write this code:

[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(animationDidStop:context:)];
[UIView commitAnimations];

But you need to few lines of code if you are using a block like below:

[UIView animateWithDuration:2.0 animations:^{
// set up animation
} completion:^{
// this will be executed on completion
}];

Hope you are clear now about the use of the block.

like image 106
nitin.agam Avatar answered Feb 13 '23 02:02

nitin.agam


  1. The major feature of the blocks is that you can determine it in the method's place where you are. It can be very convenient for reading and understanding a logic.
  2. The blocks are the alternative for callbacks.
  3. The blocks can capture state from the lexical scope within which it is defined.
like image 38
gerram Avatar answered Feb 13 '23 01:02

gerram