问题
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