UIGestureRecognizer导致"EXC_BAD_ACCESS"错误

Ber*_*rnd 4 objective-c uigesturerecognizer ios

使用附加到视图的GestureRecognizer会导致我的应用程序因EXC_BAD_ACCESS错误而崩溃.这是涉及的课程

BoardViewController - 在AppDelegate中显示设置为rootViewController的板(作为背景).它实例化"TaskViewcontroller"的多个对象.

//BoardViewController.h
@interface BoardViewController : UIViewController {
    NSMutableArray* allTaskViews; //for storing taskViews to avoid having them autoreleased
}
Run Code Online (Sandbox Code Playgroud)

 

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

TaskViewController - 板上显示的个人框.它应该是可拖动的.因此我将UIPanGestureRecoginzer附加到它的视图中

- (void)viewDidLoad
{
    [super viewDidLoad];

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

- (void)handlePan:(UIPanGestureRecognizer *)recognizer {
    NSLog(@"PAN!");
}
Run Code Online (Sandbox Code Playgroud)

.xib文件是一个简单的视图.

在此输入图像描述

使用手势识别器进行的所有编程我都希望在代码中进行.知道如何修复导致应用程序崩溃的错误吗?

das*_*ght 8

该方法handlePan位于视图控制器上,而不是视图上.您应该将目标设置为self:

UIPanGestureRecognizer* panRecognizer = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(handlePan:)];
Run Code Online (Sandbox Code Playgroud)

编辑(响应问题的编辑)正如omz正确指出的那样,你的退出TaskViewController时会被释放.有两种方法可以处理它:BoardViewControllerviewDidLoad:

  • handlePan方法折叠到父视图控制器中,以及代码viewDidLoad:
  • 创建一个实例变量TaskViewController *taskA,而不是使其成为局部变量.