如何在块中访问实例变量

时间:2012-10-10 17:10:23

标签: iphone objective-c block instance-variables

我想访问块中的实例变量,但总是在块内接收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

我不熟悉块编程,我的代码中有什么问题?

2 个答案:

答案 0 :(得分:1)

您正在访问已在不再在范围内的堆栈上分配的块。您需要将bb分配给复制的块。 bb也应该移动到类的实例变量。

//Do not forget to Block_release and nil bb on viewDidUnload
bb = Block_copy(bb);

答案 1 :(得分:0)

您应该为age ivar定义正确的访问者方法:

@interface ViewController : UIViewController{
  int age; // an instance variable
}
@property (nonatomic) int age;
...
你的.m文件中的

@implementation ViewController
@synthesize age;
...

并使用它:

    NSLog(@"%d", aa.age);// EXC_BAD_ACCESS here

如果你正确地分配了ViewController,以便在执行块之前不释放它的实例,这将解决它。