简体   繁体   中英

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM