块内的弱引用 [英] Weak references inside a block

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

问题描述

我正在使用 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.
}];

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

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