Balázs Vincze
Balázs Vincze

Reputation: 3832

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.

Upvotes: 4

Views: 1286

Answers (2)

nitin.agam
nitin.agam

Reputation: 2142

  • 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.

Upvotes: 5

gerram
gerram

Reputation: 520

  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.

Upvotes: 4

Related Questions