UIGestureRecognizer causing the error "EXC_BAD_ACCESS"

Using a GestureRecognizer connected to a view causes my application to crash with an EXC_BAD_ACCESS error. Classes involved here

β€’ BoardViewController . Displays the board (as a background) installed as rootViewController in AppDelegate. It creates several "TaskViewcontroller" objects.

//BoardViewController.h @interface BoardViewController : UIViewController { NSMutableArray* allTaskViews; //for storing taskViews to avoid having them autoreleased } 

 //BoardViewController.m - Rootviewcontroller, instantiating TaskViews - (void)viewDidLoad { [super viewDidLoad]; TaskViewController* taskA = [[TaskViewController alloc]init]; [allTaskViews addObject:taskA]; [[self view]addSubview:[taskA view]]; } 

β€’ TaskViewController . - A separate field displayed on the board. It needs to be dragged. So I applied UIPanGestureRecoginzer to his opinion

 - (void)viewDidLoad { [super viewDidLoad]; UIPanGestureRecognizer* panRecognizer = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(handlePan:)]; [[self view] addGestureRecognizer:panRecognizer]; } - (void)handlePan:(UIPanGestureRecognizer *)recognizer { NSLog(@"PAN!"); } 

The .xib file is a simple view.

enter image description here

All programming with a gesture recognizer I would prefer to do in code. Any idea how to fix the error that caused the application to crash?

+4
source share
2 answers

The handlePan method is on your view controller, not your view. You must set the target to self :

 UIPanGestureRecognizer* panRecognizer = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(handlePan:)]; 

EDIT (in response to editing the question). As omz correctly noted, your TaskViewController will be released after BoardViewController viewDidLoad: exit. There are two ways to deal with it:

  • Add the handlePan method to the parent view controller along with viewDidLoad: or
  • Make an instance variable for TaskViewController *taskA , instead of making it local.
+8
source

This is my way to use Gesture Recognizer. I think this way is easy and low risk.

First, you drag the gesture pointer into the view.

ss

Then you connect the gesture recognizer icon to the code.

ss

Finally, you write the code for this IBAction, as shown below:

 - (IBAction)handlePan:(id)sender { NSLog(@"PAN!"); } 

You can download this project from GitHub and just run it.

https://github.com/weed/p120812_PanGesture

0
source

All Articles