块内的弱引用

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

我正在使用 NSOperationQueue 并排队 NSOperationBlocks 。现在,块具有对块中任何实例的强引用,并且调用对象也具有强大的阻塞,因此建议执行以下操作:

I'm using an NSOperationQueue and queuing up NSOperationBlocks. Now, blocks have a strong reference to any instances in the block, and the calling object also has a strong hold on the block, so it has been advised to do something like the following:

__weak Cell *weakSelf = self; NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{ UIImage *image = /* render some image */ /* what if by the time I get here self no longer exists? */ [[NSOperationQueue mainQueue] addOperationWithBlock:^{ [weakSelf setImageViewImage:image]; }]; }]; [self.renderQueue addOperation:op];

所以,我的问题是,让我们说当图像完成渲染并且该行恢复时, Cell 对象不再存在(它已被解除分配,可能是由于单元重用,这有点难以形式化)。当我去访问 [weakSelf setImageViewImage:] 时,是否会导致 EXC_BAD_ACCESS 错误?

So, my question is, let's say that by the time the image finishes rendering and that line comes back, the Cell object no longer exists (it has been deallocated, possibly due to cell reuse, which is a bit difficult to formalize). When I go to access [weakSelf setImageViewImage:], will that cause a EXC_BAD_ACCESS error?

目前我正试图追查问题的原因,我认为这可能与此有关。

Currently I'm trying to trace what the cause of my problem is, and I'm thinking it might have something to do with this.

推荐答案

所以, __弱是一个归零的弱引用。这意味着在您的操作期间, self 可能确实已被释放,但所有弱引用(即 weakSelf )将被清零。这意味着 [weakSelf setImageViewImage:image] 只是向 nil 发送消息,这是安全的;或者,至少,它不应该导致 EXC_BAD_ACCESS 。 (顺便提一下,如果您将 weakSelf 限定为 __ unsafe_unretained ,则最终可能会向已释放的对象发送消息。)

So, __weak is a zeroing weak reference. What this means is that during your operation, self may indeed be deallocated, but all weak references to it (namely weakSelf) will be zeroed out. This means that [weakSelf setImageViewImage:image] is just sending a message to nil, which is safe; or, at least, it shouldn't cause an EXC_BAD_ACCESS. (Incidentally, if you had qualified weakSelf as __unsafe_unretained, you might end up sending messages to a freed object.)

因此,我怀疑向 __弱引用发送消息会导致崩溃。如果你想确保 self 在你的操作期间存活,你可以获得对块范围中弱点的强引用:

So, I doubt that sending a message to a __weak reference is causing a crash. If you want to ensure that self survives for the length of your operation, you can get a strong reference to the weak one in the block scope:

__weak Cell *weakSelf = self; NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{ Cell *strongSelf = weakSelf; // object pointers are implicitly __strong // strongSelf will survive the duration of this operation. // carry on. }];

更多推荐

块内的弱引用

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

发布评论

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

>www.elefans.com

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