2012-01-16 253 views
1

我的iPhone应用程序非常简单,但它出错。我的应用程序代理打开此视图控制器:UIButton简单应用程序 - iPhone应用程序中的错误

#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])); 
    } 
} 
+0

回溯没有有用的信息。它只是指向main.m类并没有有用的错误消息。 – CodeGuy 2012-01-16 02:32:05

+0

在'buttonPressed'的'NSLog()'上设置一个断点。 – zaph 2012-01-16 02:37:26

+0

就像我说的,没有错误信息。我在控制台上看到的最后一件事是:当前语言:auto;目前Objective-C的 (GDB) – CodeGuy 2012-01-16 02:37:36

回答

1

目标类已被释放,需要保留。

从Apple文档:

addTarget:action:forControlEvents:

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

您需要确保类的实例被保留。

+0

类是“自我”... – CodeGuy 2012-01-16 05:29:35

+0

该类似乎是ViewController。它在某处被实例化,需要保留。 – zaph 2012-01-16 11:52:15

1

将其更改为:

@selector(buttonPressed:) //add the :

,并使用此:

-(IBAction)buttonPressed:(id)sender;

按钮是要求的动作。

+0

这不是iOS需要的,iOS接受三种形式的目标方法:不带参数,仅限发件人或发件人和事件。另外:MacOS不具备这种灵活性。 – zaph 2012-01-16 03:58:19

+0

OH,UH我做了一个嘘声,你是对的,这些参数在iOS中是可选的。其实他的代码的作品,它必须是别的... – 2012-01-16 04:10:43