2
- (void)viewDidLoad
{
    [super viewDidLoad];

}

-(id)init{
    self = [super initWithNibName:@"WritingView"   bundle:nil ];
    if (self) {
        //self.view.delegate = self;
        self.txtMain.userInteractionEnabled = YES;
        self.txtMain.delegate = self;

    }
    return self;
}

-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    return [self init];
}

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{

    NSLog(@"textViewShouldBeginEditing:");

    return YES;

}

self.txtMain 是我在 xib 中的根视图:WritingView,我的视图控制器实现了协议 UITextViewDelegate ,像这样:

@interface WritingViewController : UIViewController<UITextViewDelegate>
{

}
@property (strong, nonatomic) IBOutlet UITextView *txtMain;

我在 UITextViewDelegate 中的 textViewShouldBeginEditing 或其他函数中设置了断点,但为什么从来没有进入?顺便说一下,这个 ViewController 是由另一个 ViewController 创建的,像这样:

WritingViewController *aViewController = [[WritingViewController alloc] initWithNibName:@"WritingView"   bundle:nil];

[self.view.superview addSubview:aViewController.view];
[self.view removeFromSuperview];

谁能告诉我为什么它不起作用,然后我更改了初始化代码:

-(id)init{
    self = [super initWithNibName:@"WritingView"   bundle:nil ];
    if (self) {
        UITextView *txtView = [[UITextView alloc] initWithFrame:self.view.frame];

        txtView.textColor = [UIColor blackColor];
        txtView.font = [UIFont fontWithName:@"Arial" size:18.0];
        txtView.text =  @"Now is the time for all good developers tocome to serve their country.\n\nNow is the time for all good developers to cometo serve their country.";//

        self.txtMain = txtView;
        self.txtMain.userInteractionEnabled = YES;
        self.txtMain.delegate = self;
        [self.view addSubview:txtView];

    }
    return self;
}

显然我使用了一个空白视图作为根视图,但这一次,当我点击文本时,程序在 main() 中崩溃了:

      return UIApplicationMain(argc, argv, nil, NSStringFromClass([WheelDemoAppDelegate class]));

在控制台中:</p>

2013-11-03 22:53:57.514 Wheel demo[1718:a0b] *** -[WritingViewController respondsToSelector:]: message sent to deallocated instance 0x9b4eeb0

(lldb)

4

2 回答 2

1

您需要以某种方式确保 ARC 系统不会从内存中删除您的对象。一旦对象的保留计数达到零,ARC 就会删除对象,并且对象不再在范围内。ARC 系统与垃圾收集器非常不同。您可能想阅读它:https ://developer.apple.com/library/mac/releasenotes/ObjectiveC/RN-TransitioningToARC/Introduction/Introduction.html

你得到的错误是没有保留你的视图控制器(WritingViewController)的结果。尝试在创建视图控制器的类上创建一个属性:

@property (nonatomic,strong) WritingViewController *writtingVc;

并在您创建它之后立即将其设置为您的 WritingViewController 实例。

于 2013-11-03T15:57:51.997 回答
0

你的第一个代码不起作用,因为当你打电话时

    self.txtMain.userInteractionEnabled = YES;
    self.txtMain.delegate = self;

在您的单元方法中,尚未加载视图。这意味着你的txtMain不存在。

要修复,请将该代码放入viewDidLoad而不是init.

于 2013-11-03T15:24:37.513 回答