Block没有在typeof中捕获self,为什么?

Block didn’t capture self in typeof,why?

为此:

self.block = ^{
    self.view.backgroundColor = [UIColor greenColor];
};

明显有一个retain cycle

但是,如果selftypeof中,则没有保留周期:

__weak typeof(self) weakSelf = self;
self.block = ^{
    __strong typeof(self) strongSelf = weakSelf;
    strongSelf.view.backgroundColor = [UIColor greenColor];
};

即使 self 在 block.That 中,也会调用自己的 dealloc 意味着该块未在此处捕获 self

为什么?

typeof 不是一个函数,它是一个关键字,根本不在运行时使用。 __strong typeof(self) 在这里所做的就是告诉编译器如何计算符号 strongSelf。它不会导致生成任何运行时代码,因为在运行时实际上该类型是什么并不重要。所有这些决定都是在编译时做出的。

这与将某物定义为 int x; 相同。运行时不会以任何方式引用 "int"。只是一个C类型。

typeof 在技术上是一个 C 扩展,但 Clang 在默认的 gcc 兼容模式下支持它作为关键字。有关扩展的更多信息,请参阅 GCC documentation.