澄清弱引用和保留周期 [英] Clarification about weak references and a retain cycles

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

问题描述

我有以下代码:

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest: request];

operation.completionBlock = ^{
    if([operation hasAcceptableStatusCode]){

    }
};

ARC似乎不喜欢[operation hasAcceptableStatusCode],并且出现以下警告:在此块中强烈捕获'operation'可能会导致保留周期".

ARC doesn't seem to like [operation hasAcceptableStatusCode], and i get the following warning: "Capturing 'operation' strongly in this block is likely to lead to a retain cycle".

我对引用不是很有经验,知道要怎么走吗?

I'm not very experienced with referencing, any idea whats the way to go here?

谢谢,

推荐答案

块从外部捕获(保留)您引用的对象.

Blocks capture (retain) the objects that you reference from outside of them.

操作将保留completeBlock,它将保留操作,因此将保留循环.

operation will retain completionBlock which will retain operation, hence the retain cycle.

最好的办法是创建对该对象的弱引用,并将其传递给它

The best thing to do is create a weak reference to the object and pass that in instead

AFHTTPRequestOperation * __weak theOperation = operation

operation.completionBlock = ^{
    if (theOperation) {
        return;
    }
};

弱引用在运行时是安全的,因此,如果已取消分配操作,则只会向nil发送一条消息.

Weak references are safe at runtime so if operation has been dealloced you will just send a message to nil.

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

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