Is there a SELF pointer for blocks?

前端 未结 4 1587
粉色の甜心
粉色の甜心 2020-12-25 14:09

I\'d like to recursively call a block from within itself. In an obj-c object, we get to use \"self\", is there something like this to refer to a block instance from inside i

4条回答
  •  滥情空心
    2020-12-25 14:51

    Fun story! Blocks actually are Objective-C objects. That said, there is no exposed API to get the self pointer of blocks.

    However, if you declare blocks before using them, you can use them recursively. In a non-garbage-collected environment, you would do something like this:

    __weak __block int (^block_self)(int);
    int (^fibonacci)(int) = [^(int n) {
        if (n < 2) { return 1; }
        return block_self(n - 1) + block_self(n - 2);
    } copy];
    
    block_self = fibonacci;
    

    It is necessary to apply the __block modifier to block_self, because otherwise, the block_self reference inside fibonacci would refer to it before it is assigned (crashing your program on the first recursive call). The __weak is to ensure that the block doesn't capture a strong reference to itself, which would cause a memory leak.

提交回复
热议问题