如何在块中访问实例变量

3

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

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

请发布您的年龄声明。 - danh
2个回答

1

您正在访问已分配在不再在作用域内的堆栈上的块。 您需要将bb 分配给复制的块。 bb还应移动到类的实例变量中。

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

如果这是你的完整类,那么你还需要在dealloc方法中释放bb - Joe
谢谢。这只是一个演示。我知道问题出在哪里。我发现了一种奇怪的语法:如果像这样定义bb,@property(nonatomic, copy) BB bb; 那么我可以在 foo() 方法中使用 self.bb();来调用它。 - tristan

0
你应该为你的age实例变量定义正确的访问器方法:
@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,使得它的实例在块执行之前不会被释放,这将解决问题。

1
如果age是私有的,那么属性并不是必需的。 - Joe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接