简体   繁体   中英

Blocks for Passing Data between VC's - EXC_BAD_ACCESS

I'm using blocks to pass data from a view controller, VC3, which appears within a modal view that is pushed by VC1. The modal displayed is VC2, and it shows VC3 before being dismissed.

I am getting a EXC_BAD_ACCESS error when using the blocks.

Below is the code.

VC1.m

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
self.VC2 = [storyboard instantiateViewControllerWithIdentifier:@"VC2"];

VC3 *VC3 = [storyboard instantiateViewControllerWithIdentifier:@"VC3"];

VC3.onDismiss = [^(VC3 *sender, NSMutableArray *details)
{
    //set stuff here

} copy];
[self presentViewController:VC2 animated:YES completion:nil];

VC3.h

@property (nonatomic, strong) void (^onDismiss)(VC3 *sender, NSMutableArray* details);

VC3.m

 [self dismissViewControllerAnimated:YES completion:^{
   NSMutableArray *details = [NSMutableArray array];
    [details addObject:x];
    [details addObject:y];
    [details addObject:z];

    self.onDismiss(self, details);
}];

I've tried and failed to get this working a few times. If someone could help me with this, I would be really grateful.

  1. Block properties should be declared as copy

     @property (nonatomic, copy) void (^simpleBlock)(void); 
  2. Then, when passing the block, don't call the copy method on it.

     VC3.onDismiss = ^(VC3 *sender, NSMutableArray *details) { // do stuff here }; 
  3. Finally, you should check if the block is not nil before executing it.

Problem

It looks like you're invoking the block after the view controller was dismissed. This means you're trying to access deallocated memory. Problem lays here:

 [self dismissViewControllerAnimated:YES completion:^{
   NSMutableArray *details = [NSMutableArray array];
    [details addObject:x];
    [details addObject:y];
    [details addObject:z];

    self.onDismiss(self, details);
}];

You dismiss the controller and then in completion handler you access it's property.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM