Delegate assignment causes EXC_BAD_ACCESS

2020-05-09 23:29发布

I am trying to create a delegate for an NSTextField in my view controller, but the program crashes with EXC_BAD_ACCESS. Why does this happen? I read that I am calling a non-existent object, but I don´t know what does not exist. I am using ARC.

This is how the delegate object is created in my view controller:

#import <Cocoa/Cocoa.h>
#import "Delegate.h"

@interface ViewController : NSViewController <NSTextFieldDelegate>{
}
@end

--

#import "ViewController.h"
@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    NSTextField* textField1 = [[NSTextField alloc] initWithFrame:NSMakeRect(200, 200, 150, 20)];
    [self.view addSubview:textField1];

    Delegate* delegate1 = [[Delegate alloc]init];
    [textField1 setDelegate:delegate1];
}

@end

Why does my program crash?

1条回答
够拽才男人
2楼-- · 2020-05-09 23:56

I think the delegate1 is release, in viewDidLoad

Delegate* delegate1 = [[Delegate alloc]init];

You should create a var for handling it in ViewController.h. Then

delegate1 = [[Delegate alloc]init];

查看更多
登录 后发表回答