objective-c - Objective-C 中的weakSelf 和strongSelf

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

如果 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)由编译器作为编译时 - 在生成的编译代码中没有使用 typeoftypeof 的主要用途是在 #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/

相关文章:

ios - 水平均匀分布三个按钮ios

iphone - 圆形自定义按钮的事件区域较小

ios - 在 iOS 上,是否需要执行 CGContextRelease?

c++ - Objective-C block 、C++ 变量和异步代码

iphone - 在实例变量中保存 block

c++ - iOS debugBlock 宏

ios - ios 视频中图像位置的变化

ios - iphone 应用程序因内存压力而崩溃

objective-c - 如果我在使用 ARC 时未能初始化变量,clang 如何警告我?

swift - 为什么我的 Objective-C block 在传递给 Swift 函数时没有显示?