iOS 5中用于IBAction的EXC_BAD_ACCESS

时间:2012-02-02 06:06:26

标签: iphone ios5 xcode4.2

我已经在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

4 个答案:

答案 0 :(得分:1)

首先将此代码更改为此代码

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

答案 1 :(得分:1)

我找到了解决问题的方法。

主要问题是,如果我在本地创建一个视图控制器对象(即在任何方法内)并将其添加为子视图,那么当你调用任何IBAction时,它会引发异常,因为,当在本地声明时,该viewController的内存将被自动释放。

答案 2 :(得分:0)

我猜他也需要为该按钮添加数据成员。我的意思是代码应该是这样的。

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

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

并尝试替换

@synthesize button = _button;

@synthesize button;
<。>在您的.m文件中。

答案 3 :(得分:-1)

您的changed操作的邮件签名错误。它应该是:

- (IBAction)changed:(id)sender

并在addTarget代码行中:

@selector(changed:)

PS:你为什么使用_button?我不认为这与问题有关,但您应该使用self.button代替。应该避免直接访问实例变量,尤其是在这种情况下,允许编译器决定变量应该具有的名称。

PPS:正如@InderKumarRathore所提到的,在运行自己的代码之前,你也应该调用[super viewDidLoad]