Is there a SELF pointer for blocks?

前端 未结 4 1588
粉色の甜心
粉色の甜心 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:44

    There is no self for blocks (yet). You can build one like this (assuming ARC):

    __block void (__weak ^blockSelf)(void);
    void (^block)(void) = [^{
            // Use blockSelf here
    } copy];
    blockSelf = block;
        // Use block here
    

    The __block is needed so we can set blockSelf to the block after creating the block. The __weak is needed because otherwise the block would hold a strong reference to itself, which would cause a strong reference cycle and therefore a memory leak. The copy is needed to make sure that the block is copied to the heap. That may be unnecessary with newer compiler versions, but it won't do any harm.

提交回复
热议问题