recursive blocks in Objective-C

Define another reference to the block, to be captured in the block itself.

The __block attribute ensures that weakBlock isn't captured by value before being set.

The __weak attribute prevents the two block references keeping each other alive forever.

__weak __block void (^weakBlock)(int i);

void (^strongBlock)(int) = ^(int i) {
  NSLog(@"%d", i);
  if (i < 3) {
    weakBlock(i+1);
  }
};

weakBlock = strongBlock;
strongBlock(1);

Output:

1
2
3

From a discussion here.