如果 block 内有很多对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
是一个(目标)C 语言扩展,它在声明中(此处声明 strongSelf
)由编译器作为编译时 - 在生成的编译代码中没有使用 typeof
。 typeof
的主要用途是在 #define
宏中,它允许扩展单个宏以处理不同的类型;这种宏扩展再次发生在编译时。
在您的情况下,您正在实例方法中构造一个 block ,抽象而言您的代码将类似于:
@implementation SomeClass {
- (someReturnType) someInstanceMethod {
... ^{ typeof(self) strongSelf = weakself; ... } ...
} }
这里typeof(self)
实际上只是SomeClass
的“简写”。 self
的使用是在编译时处理的,并且不会捕获对 self
引用的运行时对象的引用。
Both versions are used 50/50. Are the both correct?
它们的含义相同。 ARC 规则规定,如果不存在限定符,则假定为 __strong
,因此一个版本依赖于此,而另一个版本则明确限定符。
HTH
关于objective-c - Objective-C 中的weakSelf 和strongSelf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52584647/