UIButton触摸应用程序崩溃

时间:2012-04-11 15:28:41

标签: iphone objective-c

我有一个navigationController,它包含一些按钮的视图,但是当我按下一个按钮时,我收到一个EXC_BAD_ACCESS错误。因为目标设定正确,我无法想象我做错了什么。它是否以编程方式或通过IB添加按钮时崩溃。

按钮代码:

UIButton *reportsButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
reportsButton.frame = CGRectMake(20, 100, 100, 50);
[reportsButton setTitle:@"Reports" forState:UIControlStateNormal];
[reportsButton addTarget:self action:@selector(reportsButtonTouched:) forControlEvents:UIControlEventTouchUpInside];

功能按钮正在尝试访问:

- (void)reportsButtonTouched:(id)sender
{
    NSLog(@"working");
}

错误:

int main(int argc, char *argv[])
{
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); //EXC_BAD_ACCESS code=1
}

按钮尝试访问的功能存在。

也许这与我不知道的NavigationController功能有关,但我之前没有遇到任何问题。

感谢您的回答,我真的非常感谢我之前从这个网站获得的帮助。

编辑:这是我的AppDelegates didFinishLaunching incase,无论如何都有帮助。

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    UIViewController *homevc = [[HomeViewController alloc] initWithNibName:@"HomeViewController" bundle:nil];

    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:homevc];

    [self.window addSubview:nav.view];
    [self.window makeKeyAndVisible];
    return YES;
}

2 个答案:

答案 0 :(得分:4)

您的代码中的任何内容似乎都没有指出任何问题。 Use this tutorial使Xcode在所有异常中中断。这将使你更接近“犯罪现场”,而不是崩溃到主要。

答案 1 :(得分:1)

我也遇到了这个错误;我一直在使用SpriteKit进行编程并以某种方式实现我的按钮,然后当我回到不使用框架时,我突然实现的每个按钮都会导致错误的访问错误。

我发现我正在viewDidLoad中初始化我的按钮,因为我一直在使用didMoveToView,并且我不小心将它们视为同一个函数(说实话我并没有真正掌握viewDidLoad实际上做了什么)。

但是当我这样做时:

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

}
return self;
}


- (void)addButton
{
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 45, 45)];

[button setTitle:@"CLICK" forState:UIControlStateNormal];


[button addTarget:self action:@selector(buttonPressed:) 
forControlEvents:UIControlEventTouchDown];

[self.view addSubview:button];
}

- (void)buttonPressed:(UIButton *)button
{
    NSLog(@"WORKED"); 
}

一切都很好......所以试试看,如果你还有麻烦的话。 祝你好运!