Objective c 委托分配导致EXC\u访问错误
我正试图为视图控制器中的Objective c 委托分配导致EXC\u访问错误,objective-c,cocoa,memory-management,automatic-ref-counting,exc-bad-access,Objective C,Cocoa,Memory Management,Automatic Ref Counting,Exc Bad Access,我正试图为视图控制器中的NSTextField创建一个委托,但程序因EXC\u BAD\u访问而崩溃。为什么会发生这种情况?我读到我正在调用一个不存在的对象,但我不知道什么是不存在的。我正在使用ARC 以下是在“我的视图控制器”中创建代理对象的方式: #import <Cocoa/Cocoa.h> #import "Delegate.h" @interface ViewController : NSViewController <NSTextFieldDelegate>
NSTextField
创建一个委托,但程序因EXC\u BAD\u访问而崩溃。为什么会发生这种情况?我读到我正在调用一个不存在的对象,但我不知道什么是不存在的。我正在使用ARC
以下是在“我的视图控制器”中创建代理对象的方式:
#import <Cocoa/Cocoa.h>
#import "Delegate.h"
@interface ViewController : NSViewController <NSTextFieldDelegate>{
}
@end
为什么我的程序会崩溃?我认为delegate1
在viewDidLoad
Delegate*delegate1=[[Delegate alloc]init]代码>
您应该在ViewController.h
中创建一个var来处理它。然后
delegate1=[[Delegate alloc]init]
我在Viewcontroller.h
中创建了我的委托的一个实例:delegate*delegate我删除了委托*delegate1=[[Delegate alloc]init]代码>在Viewcontroller.m
中。它仍然不会在控制台中打印“ABC”;(.但这次不会崩溃;)不要删除它。请试试我的答案。替换为delegate1=[[Delegate alloc]init]代码>非常感谢!现在可以了。但是为什么我必须在视图控制器的界面和实现中一次写入delegate1
?我知道它将“ABC”打印到控制台中,但不创建文本字段。为什么委托方法不创建新的文本字段?因为如果没有任何指针来处理delegate1
。它将被发布。对于textfield,检查IBOutlet window1,以及window1与textfield的框架
#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