Clarification about weak references and a retain cycles

自作多情 提交于 2019-12-10 09:30:44

问题


I have the following code:

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

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

    }
};

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?

Thanks,
Shai


回答1:


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

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;
    }
};

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



来源:https://stackoverflow.com/questions/8203081/clarification-about-weak-references-and-a-retain-cycles

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!