4

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

Brad Larson
  • 170,088
  • 45
  • 397
  • 571
Shai Mishali
  • 9,224
  • 4
  • 56
  • 83

1 Answers1

6

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.

jackslash
  • 8,550
  • 45
  • 56