2012-01-16 252 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