是否有用于块的SELF指针? [英] Is there a SELF pointer for blocks?

查看:78
本文介绍了是否有用于块的SELF指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从自身内部递归调用一个块.在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指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆