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

前端 未结 2 1681
既然无缘
既然无缘 2021-01-13 05:01

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 funct

2条回答
  •  旧巷少年郎
    2021-01-13 05:31

    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.

提交回复
热议问题