我想访问块中的实例变量,但总是在块中接收 EXC_BAC_ACCESS。我在我的项目中不使用 ARC。
.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
我不熟悉块编程,我的代码有什么问题?