To better illustrate the question, consider the following simplified form of block recursion:
__block void (^next)(int) = ^(int index) {
if (index == 3) {
return;
}
int i = index;
next(++i);
};
next(0);
XCode (ARC-enabled) warns that "Capturing 'next' strongly in this block is likely to lead to a retain cycle".
Agreed.
Question 1: Would the retain cycle be successfully broken by setting the block itself to nil, in this fashion:
__block void (^next)(int) = ^(int index) {
if (index == 3) {
next = nil; // break the retain cycle
return;
}
int i = index;
next(++i);
};
next(0);
(Note: you'd still get the same warning, but perhaps it is unwarranted)
Question 2: What would be a better implementation of block recursion?
Thanks.
__block int ibecause it is modified in the next line of code. - krisknextisn't bound within the Block until it's excuted due to its__blockstorage specifier. bbum's Block Tips and Tricks post has something about this. At any rate, recursive blocks are certainly possible. - jscsnextis uninitialized when the block is created. However,nextis a__blockvariable, which is captured by reference. Thenextseen inside the block reflects the value ofnextwhen the block executes, which is after the assignment tonext. - newacct