问题描述
我想从自身内部递归调用一个块.在obj-c对象中,我们可以使用自我",是否有这样的东西从自身内部引用一个块实例?
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 itself?
推荐答案
有趣的故事!块实际上是Objective-C对象.也就是说,没有公开的API可以获取块的self
指针.
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;
将__block
修饰符应用于block_self
是必要的,因为否则,fibonacci
中的block_self
引用将在分配它之前对其进行引用(使程序崩溃)第一次递归调用). __weak
是为了确保该块不会捕获对其自身的强引用,否则会导致内存泄漏.
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.
这篇关于是否有用于块的SELF指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!