簡體   English   中英

適用於IBAction的iOS5中的EXEC_BAD_ACCESS

[英]EXEC_BAD_ACCESS in iOS5 for IBAction

我為iOS5的xcode 4.2中的按鈕單擊操作編寫了示例代碼。

這是代碼

。H

#import <UIKit/UIKit.h>

@interface FirstViewController : UIViewController


@property(strong,nonatomic) IBOutlet UIButton *button;
-(IBAction)changed;
 @end

.m

#import "FirstViewController.h"

@implementation FirstViewController

@synthesize button=_button;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self)
    {
        // Custom initialization
    }
    return self;
}    

- (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
{

    [_button addTarget:self action:@selector(changed)     forControlEvents:UIControlEventTouchUpInside];
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
-(IBAction)changed
{
    NSLog(@"clicked");

    }
    - (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 YES;
}

@end

但是當我單擊按鈕時。 我正在例外。 如何解決這個問題? 在iOS 4.3中也是如此

我已經找到解決問題的方法。

主要問題是,如果我在本地(即在任何方法內部)創建一個視圖控制器對象並將其添加為子視圖,則當您調用任何IBAction時,這將引發異常,因為該viewController的內存為在本地聲明時自動釋放。

首先將此代碼更改為此

- (void)viewDidLoad
{
    [super viewDidLoad];
// Do any additional setup after loading the view from its nib.
    [_button addTarget:self action:@selector(changed) forControlEvents:UIControlEventTouchUpInside];
}

我猜他也需要為該按鈕添加數據成員。 我的意思是代碼應該看起來像這樣。

@interface FirstViewController : UIViewController{
  IBOutlet *UIButton *button;
}

@property(strong,nonatomic) IBOutlet UIButton *button;
-(IBAction)changed;
 @end

並嘗試更換

@synthesize button = _button;

@synthesize button;

在您的.m文件中。

您所changed操作的消息簽名錯誤。 它應該是:

- (IBAction)changed:(id)sender

並在代碼的addTarget行中:

@selector(changed:)

PS:為什么使用_button 我認為這與問題無關,但是您應該改用self.button 應避免直接訪問實例變量,尤其是在這種情況下,在這種情況下,編譯器可以決定變量應使用的名稱。

PPS:如@InderKumarRathore所述,您還應該在運行自己的代碼之前調用[super viewDidLoad]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM