D.8Ge D.8Ge - 1 year ago 212
Objective-C Question

Using a block in Object-C, I get "Thread 1:EXC_BAD_ACCESS(code=1,address=0x0)"

I want to add GestureRecognizer on an imageView and use a block in the clickAction.

But when I run it, I get this error in the block:


Thread 1:EXC_BAD_ACCESS(code=1,address=0x0)


#import "blockImage.h"

@implementation blockImage

-(instancetype)init{
if (self = [super init]) {
self = [[blockImage alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
self.tag = 10;
self.backgroundColor = [UIColor redColor];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapActionWithBolck:)];
[self addGestureRecognizer:tap];

}
return self;
}


-(void)tapActionWithBolck:(void(^)(NSInteger idx))completion{

completion(10);
}
@end


and

#import "ViewController.h"
#import "blockImage.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];

blockImage *img = [[blockImage alloc] init];
[self.view addSubview:img];

}

@end

Answer Source

You can not use method like this with UITapGestureRecognizer

-(void)tapActionWithBolck:(void(^)(NSInteger idx))completion;

it should be like that

-(void)tapAction:(UIGestureRecognizer *)sender;

or

-(void)tapAction;

If you want to use block on tap, you should keep it in variable (in init for example) and than call it in method. But keep in mind about retain cycles.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download