Objective-C

时间:2018-10-01 04:40:42

标签: objective-c automatic-ref-counting objective-c-blocks

如果在块内有很多对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。两者都正确吗?

1 个答案:

答案 0 :(得分:2)

  

当我们写typeof(self)时不是错误的吗?这里允许引用自我吗?

(A)不(B)是

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

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

@implementation SomeClass {

- (someReturnType) someInstanceMethod {

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

} }

typeof(self)实际上只是SomeClass的“简写”。 self的使用是在编译时处理的,没有捕获到self所引用的运行时对象的引用。

  

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

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

HTH

相关问题