2 lpploverou LPPloveROU 于 2012.10.16 11:22 提问

如何在块中获取实体变量?

访问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

为什么会这样?

2个回答

lanhailvcao
lanhailvcao   2012.10.16 13:36
已采纳

你访问的block块已经在堆栈上分配了;你需要为块指定bb。bb也需要放在类的实体变量中。

  bb= Block_copy(bb);
LPPloveROU
LPPloveROU 实现了。谢谢~
大约 5 年之前 回复
MrsSeven7
MrsSeven7   2012.10.17 10:42

先给age设定一个访问函数:

@interface ViewController : UIViewController{
  int age; // an instance variable
}
@property (nonatomic) int age;
...

在m文件中,

@implementation ViewController
@synthesize age;
...

然后设置:

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

如果你分配了适当的ViewController,在block执行前实例不释放

Csdn user default icon
上传中...
上传图片
插入图片