UIButton简单的应用程序 - iPhone应用程序中的错误

时间:2012-01-16 02:27:31

标签: iphone ios uibutton

我的iPhone应用程序非常简单,但它出错了。我的app delegate打开了这个视图控制器:

#import "Launch.h"

@implementation Launch

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor redColor];

    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.frame = CGRectMake(100, 100, 100, 100);
    [button setTitle:@"Hello" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonPressed) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}

-(void)buttonPressed {
    NSLog(@"Button Pressed!");
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)img editingInfo:(NSDictionary *)editInfo {
    //image.image = img;
    [[picker parentViewController] dismissModalViewControllerAnimated:YES];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end

这只是一个带按钮的红色屏幕。当我单击按钮时,应用程序出错,没有错误消息。为什么呢?

这是我的main.m方法,当程序出错时,它指向“返回”行并指示线程中的EXEC_BAD_ACCESS。

#import <UIKit/UIKit.h>

#import "testAppDelegate.h"

int main(int argc, char *argv[])
{
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([testAppDelegate class]));
    }
}

2 个答案:

答案 0 :(得分:1)

将其更改为:

@selector(buttonPressed:) //add the :

并使用此:

-(IBAction)buttonPressed:(id)sender;

按钮正在请求操作。

答案 1 :(得分:1)

目标类已被解除分配,需要保留。

来自Apple文档:

addTarget:action:forControlEvents:

  

调用此方法时,不会保留目标。

您需要确保保留类实例。