Recursive Block Retain Cycles

前端 未结 6 961
心在旅途
心在旅途 2020-12-13 04:44

Will this lead to any sort of retain cycle? Is it safe to use?

__block void (^myBlock)(int) = [^void (int i)
{
    if (i == 0)
        return;

    NSLog(@\"         


        
6条回答
  •  醉梦人生
    2020-12-13 05:35

    Here is a modern solution to the problem:

    void (^myBlock)();
    __block __weak typeof(myBlock) weakMyBlock;
    weakMyBlock = myBlock = ^void(int i) {
        void (^strongMyBlock)() = weakMyBlock; // prevents the block being delloced after this line. If we were only using it on the first line then we could just use the weakMyBlock.
        if (i == 0)
            return;
    
        NSLog(@"%d", i);
        strongMyBlock(i - 1);
    };
    myBlock(10);
    

提交回复
热议问题