So I’ve been holding off asking this question for a while because I know the solution will most likely be something very very simple. But I have come to the end of my tether so here goes:
I have created a UIButton programatically and linked it to a method, but it is not working!!
.h definition
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface CreaterPage : UIViewController
{
IBOutlet UIView *postcardView;
IBOutlet UIButton *returnButton;
}
-(void)goBack:(UIButton *)button;
@end
.m definition
#import "CreaterPage.h"
@implementation CreaterPage
-(void)viewDidLoad
{
NSLog(@"Creater Page View Loaded Successfully");
UIButton *goHomeButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[goHomeButton addTarget:self action:@selector(goBack:) forControlEvents:UIControlEventTouchDown];
[goHomeButton setTitle:@"Go Back" forState:UIControlStateNormal];
goHomeButton.frame = CGRectMake(100, 100, 100, 100);
[self.view addSubview:goHomeButton];
}
-(void)goBack:(UIButton *)button
{
NSLog(@"Home");
}
@end
And basically, when I run the code, the button appears as defined but my program crashes whenever I press it.
In the main.m file, it gives me the error
Thread 1: Program received signal: “EXC_BAD_ACCESS”.
On the line
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
I’ve tried all sorts and only turned to creating it programatically because I couldn’t get it working through the interface builder.
So I’m hoping somebody on here can change my juvenile ways and show me where I’m going wrong 😀
Thanks,
Matt
EDIT 1: Changed @selector(goBack) to @selector(goBack:)
My first guess would be that your action is defined as such:
Note the
@selector(goBack)without a colon following the method name. Your method in your.mfile is defined as:So I imagine changing your action to
@selector(goBack:)would clear things up.Sidenote: It’s very uncommon to define the type of the sender for an
IBAction, as you have done. While you might not encounter any issues as long as yourUIButtonis the only UI object that causes the method to be called, it’s very poor practice. You should change your method signature to:Note also the use of
IBActionin place ofvoid. While they’re syntatically the same thing, theIBActionmakes it clear to readers, and to Interface Builder, which methods are available for linking.