强烈引用块内的弱引用

编程入门 行业动态 更新时间:2024-10-12 01:24:20
本文介绍了强烈引用块内的弱引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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.

更多推荐

强烈引用块内的弱引用

本文发布于:2023-11-08 06:36:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1568612.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!