访问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);
先给age设定一个访问函数:
@interface ViewController : UIViewController{
int age; // an instance variable
}
@property (nonatomic) int age;
...
在m文件中,
@implementation ViewController
@synthesize age;
...
然后设置:
NSLog(@"%d", aa.age);
如果你分配了适当的ViewController,在block执行前实例不释放