I want to access an instance variable in the block, but always receive EXC_BAC_ACCESS within block.I don’t use ARC in my project.
.h file
@interface ViewController : UIViewController{
int age; // an instance variable
}
.m file
typedef void(^MyBlock) (void);
MyBlock bb;
@interface ViewController ()
- (void)foo;
@end
@implementation ViewController
- (void)viewDidLoad{
[super viewDidLoad];
__block ViewController *aa = self;
bb = ^{
NSLog(@"%d", aa->age);// EXC_BAD_ACCESS here
// NSLog(@"%d", age); // I also tried this code, didn't work
};
Block_copy(bb);
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(10, 10, 200, 200);
[btn setTitle:@"Tap Me" forState:UIControlStateNormal];
[self.view addSubview:btn];
[btn addTarget:self action:@selector(foo) forControlEvents:UIControlEventTouchUpInside];
}
- (void)foo{
bb();
}
@end
I’m not familiar with blocks programming, what’s the problem in my code ?
You are accessing the block which was allocated on the stack which is no longer in scope. You need to assign
bbto the copied block.bbshould aslo be moved to an instance variable of the class.