簡體   English   中英

UIGestureRecognizer導致“EXC_BAD_ACCESS”錯誤

[英]UIGestureRecognizer causing “EXC_BAD_ACCESS” error

使用附加到視圖的GestureRecognizer會導致我的應用程序因EXC_BAD_ACCESS錯誤而崩潰。 這是涉及的課程

BoardViewController - 在AppDelegate中顯示設置為rootViewController的板(作為背景)。 它實例化“TaskViewcontroller”的多個對象。

//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 - 板上顯示的個人框。 它應該是可拖動的。 因此我將UIPanGestureRecoginzer附加到它的視圖中

- (void)viewDidLoad
{
    [super viewDidLoad];

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

- (void)handlePan:(UIPanGestureRecognizer *)recognizer {
    NSLog(@"PAN!");
}

.xib文件是一個簡單的視圖。

在此輸入圖像描述

使用手勢識別器進行的所有編程我都希望在代碼中進行。 知道如何修復導致應用程序崩潰的錯誤嗎?

handlePan方法位於視圖控制器上,而不是視圖上。 您應該將目標設置為self

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

編輯 (響應問題的編輯)正如omz正確指出的那樣,你的TaskViewControllerBoardViewControllerviewDidLoad: exit時被釋放。 有兩種方法可以處理它:

  • handlePan方法與viewDidLoad:或的代碼一起折疊到父視圖控制器中
  • TaskViewController *taskA一個實例變量,而不是使其成為局部變量。

這是我使用Gesture Recognizer的方法。 我認為這種方式很簡單,風險很低。

首先,將Gesture Recognizer拖放到視圖中。

SS

然后,將Gesture Recognizer圖標連接到代碼。

SS

最后,您為此IBAction編寫代碼,如下所示:

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

您可以從GitHub下載此項目並運行它。

https://github.com/weed/p120812_PanGesture

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM