Objective-C 中的 weakSelf 和 strongSelf

weakSelf and strongSelf in Objective-C

如果块中有很多对weakSelf的引用,建议创建它的强版本。代码如下所示:

__weak typeof(self) weakSelf = self;
self.theBlock = ^{
    __strong typeof(self) strongSelf = weakSelf;

    [strongSelf doSomething];
    [strongSelf doSomethingElse];
};

我关心的是上面代码中的这一行:

__strong typeof(self) strongSelf = weakSelf;

写成typeof(self)不就错了吗?此处允许引用 self 吗?

他们有时会在教程中写道:

__strong typeof(weakSelf) strongSelf = weakSelf;

两个版本都使用 50/50。两者都正确吗?

Isn't it erroneous when we write typeof(self)? Is referencing self allowed here?

(A) 没有。 (B) 是

typeof 是一个 (Objective-)C 语言扩展,在声明中(这里你声明 strongSelf)被编译器处理为 compile time - 在生成的编译代码中没有使用 typeoftypeof 的主要用途是在 #define 宏中,它可以扩展单个宏以处理不同的类型;这种宏扩展再次发生在编译时。

在您的情况下,您正在实例方法中构造一个块,抽象而言,您的代码将类似于:

@implementation SomeClass {

- (someReturnType) someInstanceMethod {

... ^{ typeof(self) strongSelf = weakself; ... } ...

} }

此处 typeof(self) 实际上只是 SomeClass 的 "shorthand"。 self 的使用在编译时处理,不会捕获对 self 引用的运行时对象的引用。

Both versions are used 50/50. Are the both correct?

意思相同。 ARC 的规则规定,如果不存在限定符,则假定 __strong,因此一个版本依赖于此,而另一个版本明确限定符。

HTH