Reputation: 759
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 ?
Upvotes: 3
Views: 345
Reputation: 57179
You are accessing the block which was allocated on the stack which is no longer in scope. You need to assign bb
to the copied block. bb
should aslo be moved to an instance variable of the class.
//Do not forget to Block_release and nil bb on viewDidUnload
bb = Block_copy(bb);
Upvotes: 1
Reputation: 69047
You should define proper accessor methods for your age
ivar:
@interface ViewController : UIViewController{
int age; // an instance variable
}
@property (nonatomic) int age;
...
in your .m file:
@implementation ViewController
@synthesize age;
...
and the use it like this:
NSLog(@"%d", aa.age);// EXC_BAD_ACCESS here
if you allocate properly ViewController so that its instance is not deallocated before the block is executed, this will fix it.
Upvotes: 0