0

How to fix ARC retain cycle in following code ?

-(void) processRequest:delegate:(id<Delegate>)delegate {

__block  Request * request;
request = [[Request alloc] completionHandler:^(Response * response){

    [delegate removeCachedRequest:request];

    if (completionHandler)
    {
        completionHandler(response);
    }

}];

}

Michał Ciuba
  • 7,876
  • 2
  • 33
  • 59
user1743514
  • 311
  • 1
  • 3
  • 21
  • 1
    Why `__block Request *request`? – Droppy Dec 11 '14 at 08:20
  • Need to access "request" variable inside a block. So __block varible is used. – user1743514 Dec 11 '14 at 09:28
  • No, you only need `__block` if you are going to *overwrite* the variable within the block. You don't do that. – Droppy Dec 11 '14 at 14:10
  • @Droppy: No, that is not true. You also need `__block` to be able to see changes to the variable outside the block after the block was created from inside the block. This is what is happening here. The `__block` IS needed. – newacct Dec 11 '14 at 21:15
  • @newacct But `request` is created outside the block and not written to within the block. – Droppy Dec 12 '14 at 08:20
  • @Droppy: It doesn't matter. `__block` is not only useful for being written to inside the block. It's also useful for being written to outside the block and being able to see it inside the block. `request` is assigned to after the block is created. That assigned value would not be visible inside the block if it were not `__block`. – newacct Dec 12 '14 at 10:50
  • Where is `request` assigned after the block is created? – Droppy Dec 12 '14 at 11:24
  • @Droppy: The assignment statement, `request = ...`. The right hand side of an assignment is evaluated before the assignment, and the right hand side is a method call, where the arguments are evaluated before the call. So 1) the block is created, then 2) the init (or `completionHandler:`) call is made, passing the block, and then 3) the return result is assigned to `request`. – newacct Dec 13 '14 at 09:19
  • Hmm that's fairly subtle, especially given the variable going out of scope when the outer method returns. – Droppy Dec 13 '14 at 11:05

0 Answers0