2

I have a AuthService class that has a method to perform asynchronous connection to login. This class has implemented NSURLConnectionDataDelegate protocol so that when the server responses, it calls the completion handler previously set by a View Controller to update UI.

This is the definition of that completion handler

@property void (^completionHandler)(LoginResult *result);

This is when the class receives server response

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    NSString *response = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];

    //Do something with the response and create an instance of LoginResult class

    self.completionHandler(loginResult);
}

If the completion handler block merely just calls NSLog to write to console the information of the login result which is passed as argument, then it runs perfectly with no error. But when I want to call methods of the ViewController that owns the block, something strange just happens.

I know that there is a retain cycle when you include an object in a block which owns that block. So this is the way how I code it.

__block typeof(self) bself = self;

[authService login:blablabla completionHandler:^(LoginResult *result) {
    [bself didReceiveLoginResult:result];
}

I assumed this will prevent from running into a retain cycle. But I got "Thread: EXC_BAD_ACESS" error when debugging.

P.S. Following codes for example run perfectly even if that property is not declared as "copy"

[authService login:blablabla completionHandler:^(LoginResult *result) {
    NSLog(@"Login %@", result.success ? @"success" : @"failed");
}
1
  • Note that didReceiveData is not the right place to call the completion handler. It can be called several times with chunks of response data. You have to accumulate the data and call the completion handler in connectionDidFinishLoading or didFailWithError:.
    – Martin R
    May 18, 2013 at 12:30

2 Answers 2

4

The property should be declared as copy otherwise the block will stay on stack and can be already deallocated when you call it.

Also, there are simple ways how to prevent a retain circle. Just release the block when you have used it, e.g.

self.completionHandler(loginResult);
self.completionHandler = nil;

No clever magic with __block is neccessary. Retain cycles are allowed when they are temporary.

Edit:

If there is no reference to self in the block, the compiler will make it a global block and it won't ever get deallocated. See http://www.cocoawithlove.com/2009/10/how-blocks-are-implemented-and.html

4
  • Oh my god! Thank you so much for helping me :) I didn't realize the simple fact that the block is stored in the stack. But I can still inspect the block object so I'm not sure whether it has been deallocated. I notice that a block object has a member called funcPtr, which is a C-style function pointer, points to an address that is no longer available.
    – Poligun
    May 18, 2013 at 11:56
  • The problem is solved after the completion handler property is declared as "copy". But It does not make sense that, when the completion handler doesn't invoke the View Controller's method, the app runs perfectly.
    – Poligun
    May 18, 2013 at 12:02
  • @Poligun Added more info about your case.
    – Sulthan
    May 18, 2013 at 12:16
  • "Also, with MRC there are simple ways how to prevent a retain circle." 1) That is independent of whether it's MRC or ARC. 2) It does make a retain cycle; it just breaks the retain cycle later.
    – newacct
    May 19, 2013 at 1:10
-1

Blocks need to be copied if you want to use them outside of the current function, so you will need to copy it before storing it in your property:

- (void)setCompletionHandler:(void (^)(LoginResult *))handler {
    _completionHandler = [handler copy];
}

Then when you assign the completion handler in your login:completionHandler: method, it will be copied before being stored in the instance variable.

In this way, the block you pass to the function will be copied before being stored in the property, and the copy will be located on the heap, not the stack, so it'll still exist when you run it later.

6
  • Thanks for helping me :) It works. But I also find that If the completion handler just calls NSLog(@"%@", loginResult), it's okay even if the property is not declared as "copy". Could you please explain why?
    – Poligun
    May 18, 2013 at 12:06
  • ARC has very interesting rules for automatic object deallocation, and it seems that in some cases the block might not be immediately deallocated if it is stored in a property elsewhere, even if it isn't copied or retained. Obviously the use of other objects within the block affects this process.
    – Greg
    May 18, 2013 at 12:12
  • i.e. the EXC_BAD_ACCESS error that you get might not necessarily be due to the block being deallocated, but rather an object that you are trying to reference from within. If you post the stack trace of the crash we will be able to understand this further.
    – Greg
    May 18, 2013 at 12:13
  • as setCompletionHandler: is a method taking a block argument, it should be responsible for memory management of the block, and not the caller
    – newacct
    May 19, 2013 at 1:11
  • @PartiallyFinite: stack blocks are not "allocated" or "deallocated"; they have automatic storage duration, as they are implemented as local variables. Once they go out of scope, they cease to exist.
    – newacct
    May 19, 2013 at 1:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.