[Xcode]What to do when EXC_BAD_ACCESS error occurs when pressing a button with UIButton?

Medium 7568736922 photo credit: KamrenB Photography via photopin cc

Hello, this is Bono.

I'm quite hooked on it, so I'll introduce it to you.

EXC_BAD_ACCESS error

Difficult to tell where the error is occurring, a troublesome error.

Apparently, it appears to be in the event of a memory-related error.

When it comes out at UIButton.

Often appears when the button is pressed.

It is often the case that a method is written as addTarget:self action:@selector(hogeHoge) but the ":" is forgotten, such as -(void)hogeHoge:(id)sender.

This time, however, there is no problem there, and the code appears to be perfect at first glance.

//ボタンを呼び出すコード
UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
cancelButton.frame = CGRectMake(100, 300, 80, 50);
[cancelButton setTitle:@"キャンセル" forState:UIControlStateNormal];
[cancelButton addTarget:self action:@selector(hogeHoge) forControlEvents:UIControlEventTouchDown];
[self.view addSubview:cancelButton];

//ボタンが押されたら実行されるメソッド
-(void)hogeHoge
{
    NSLog(@"test OK");
}

I was completely hooked on this one.

To sum up, it looks like I needed to make a change at the caller. Declare the caller in the .h file as follows

#import <UIKit/UIKit.h>
#import "Hoge2ViewController.h" //呼び出し先のviewController

@interface HogeViewController : UIViewController {
    //ここでviewControllerを宣言しておく
    Hoge2ViewController *hoge2ViewController;
}
@end

This fixed it.

The following site saved my life. Thank you!

EXE_BAD_ACCESS when clicking on a UIButton placed on a screen with addSubView | EUI - A school that teaches iPhone and android smartphone app development