Search code examples
exc-bad-accessobjective-c-blocksself

Objective C blocks and self with touch events give BAD_ACCESS


I wanted to try using a block to update an instance variable relatively to some input events.

In my UIViewController class :

@interface ViewController : UIViewController{
    CGPoint touchPoint;
    void (^touchCallback)(NSSet* touches);
}
@property(readwrite) CGPoint touchPoint;
@end

In the implementation file :

-(id) init{
if (self = [super init]){
    touchCallback = ^(NSSet* set){
        UITouch * touch= [set anyObject];
       self.touchPoint = [touch locationInView:self.view];
         };
   }
   return self;
}

In the callbacks functions I use the block :

-(void)touchesBegin:(NSSet *)touches withEvent:(UIEvent *)event{
    touchCallback(touches);
}

 -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    touchCallback(touches);  
}

I tried several things but I have a BAD_ACCESS when I use the self instance. I don't understand where is the problem.


Solution

  • You need to copy the block:

    - (id)init {
        if (self = [super init]) {
            touchCallback = [^(NSSet* set){
                UITouch * touch= [set anyObject];
                self.touchPoint = [touch locationInView:self.view];
            } copy];
        }
        return self;
    }
    

    This is because that block is created on the stack and if you want to use it later you need to make a copy to copy it to the heap. (The block will "go away" at the end of the if-statement scope)