訪問block中的實體變量。但是在block中得到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
為什麼會這樣?
你訪問的block塊已經在堆棧上分配了;你需要為塊指定bb。bb也需要放在類的實體變量中。
bb= Block_copy(bb);