NSDictionary of Blocks as argument cause overflow
objective-c, objective-c-blocks
Solution
According to the "Transitioning to ARC Release Notes", you have to copy a block stored in a dictionary (emphasis mine):
Blocks “just work” when you pass blocks up the stack in ARC mode, such as in a return. You don’t have to call Block Copy any more. You still need to use `[^{} copy]` when passing “down” the stack into `arrayWithObjects:` and other methods that do a retain.
The second method works "by chance" because `success` and `failure` are a `__NSGlobalBlock__` and not a "stack based block" that needs to be copied to the heap.
Problem
I understand blocks are objective c objects and can be put in NSDictionary directly without Block_copy when using ARC. But I got EXC_BAD_ACCESS error with this code: ``` - (void)viewDidLoad { [super viewDidLoad]; [self method1:^(BOOL result){ NSLog(@"method1WithBlock finished %d", result); }]; } - (void) method1:(void (^)(BOOL))finish{ NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:^(NSData *rcb){ finish(YES); }, @"success", ^(NSError *error){ finish(NO); }, @"failure", nil]; [self method2:dict]; } - (void) method2:(NSDictionary *)dict{ void (^success)(NSData *rcb) = [dict objectForKey:@"success"]; success(nil); } ``` If I change method1: to this, no error raised. ``` - (void) method1:(void (^)(BOOL))finish{ void (^success)(NSData *) = ^(NSData *rcb){ finish(YES); }; void (^failure)(NSError *error) = ^(NSError *error){ finish(NO); }; NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:success, @"success", failure, @"failure", nil]; [self method2:dict]; } ``` Can anybody explain why I have to use automatic variables to store the blocks before putting them to dictionary ? I am using iOS SDK 6.1.