强烈引用块内的弱引用 [英] Strong reference to a weak references inside blocks

查看:90
本文介绍了强烈引用块内的弱引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么有必要对块内的弱引用进行强引用?

Why is it necessary to have a strong reference to a weak reference inside a block?

我知道在块内部有一个弱引用将避免保留周期。但是为什么必须再次强烈提及弱者?

I understand that having a weak reference inside the block will avoid retain cycles. But why must there be a strong reference to the weak one again?

背景:

梅森这是最佳做法。


我知道在块内引用self的正确方法是在块外创建一个弱引用,然后在块内强引用该弱引用[。 ..]

I know the proper way to refer to self inside a block is to create a weak reference outside the block, and then a strong reference to that weak reference inside the block[...]

示例:

__weak typeof(self) weakSelf = self;
void (^someBlock)(id) = ^(id data){
    typeof(self) strongSelf = weakSelf;
    // code using strongSelf
});


推荐答案

想象一下,剩下的最后一个强有力的自我引用被认为是在与你的块运行的线程不同的线程上。

Imagine that the last remaining strong reference to self is held on a different thread to the one that your block runs on.

现在发生这种情况:

__weak typeof(self) weakSelf = self;
void (^someBlock)(id) = ^(id data){
    if (weakSelf != nil) {
       // last remaining strong reference released by another thread. 
       // weakSelf is now set to nil.
       [myArray addObject:weakSelf];
    }
});

这会因为向数组添加nil而导致NSInvalidArgument异常崩溃。

This will crash with an NSInvalidArgument exception for adding nil to an array.

在使用前强制引用会消除潜在的竞争条件,并确保指针始终指向同一个对象。

Making the reference strong before use removes the potential race condition and ensures that the pointer will always point to the same object.

如果你是100%确定一个对象只能被一个线程引用,这样做并不是绝对必要的。但是做出这个假设是不好的做法。

If you are 100% certain that an object will only ever be referenced by one thread, it isn't strictly necessary to do this. But it's bad practice to make that assumption.

这篇关于强烈引用块内的弱引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆