Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an advantage to using blocks over functions in Objective-C?

I know that a block is a reusable chunk of executable code in Objective-C. Is there a reason I shouldn't put that same chunk of code in a function and just called the function when I need that code to run?

like image 823
coder Avatar asked Dec 27 '11 17:12

coder


People also ask

What does __ block do in Objective-C?

The __block Storage Type __block variables live in storage that is shared between the lexical scope of the variable and all blocks and block copies declared or created within the variable's lexical scope.

Can I use C in Objective-C?

You really can't use C in Objective-C, since Objective-C is C. The term is usually applied when you write code that uses C structures and calls C functions directly, instead of using Objective-C objects and messages.


2 Answers

It depends on what you're trying to accomplish. One of the cool things about blocks is that they capture local scope. You can achieve the same end result with a function, but you end up having to do something like pass around a context object full of relevant values. With a block, you can do this:

int num1 = 42;
void (^myBlock)(void) = ^{
    NSLog(@"num1 is %d", num1);
};

num1 = 0; // Changed after block is created

// Sometime later, in a different scope

myBlock();              // num1 is 42

So simply by using the variable num1, its value at the time myBlock was defined is captured.

From Apple's documentation:

Blocks are a useful alternative to traditional callback functions for two main reasons:

  1. They allow you to write code at the point of invocation that is executed later in the context of the method implementation. Blocks are thus often parameters of framework methods.

  2. They allow access to local variables. Rather than using callbacks requiring a data structure that embodies all the contextual information you need to perform an operation, you simply access local variables directly.

like image 120
Andrew Madsen Avatar answered Sep 27 '22 17:09

Andrew Madsen


As Brad Larson comments in response to this answer:

Blocks will let you define actions that take place in response to an event, but rather than have you write a separate method or function, they allow you to write the handling code right where you set up the listener for that event. This can save a mess of code and make your application much more organized.

A good example of which i can give you is of alert view, it will be good if i decided at time of creation of alert view what will happen when i dismiss that instead i write the delegate method and wait for that to call. So it will be much easier to understand and implement and also it provides fast processing.

like image 37
rishi Avatar answered Sep 27 '22 19:09

rishi