为什么这个委托不适用于UITextView

时间:2013-11-03 14:55:38

标签: ios delegates uitextview

- (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,我的视图控制器实现了protol UITextViewDelegate,如下所示:

@interface WritingViewController : UIViewController<UITextViewDelegate>
{

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

我在textViewShouldBeginEditing或UITextViewDelegate中的其他函数中创建了断点,但从来没有为什么? 顺便说一下,这个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]));

并在控制台中:

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

(lldb)

2 个答案:

答案 0 :(得分:1)

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

您获得的错误是未保留视图控制器(WritingViewController)的结果。尝试在创建viewcontroller的类上创建一个属性:

@property (nonatomic,strong) WritingViewController *writtingVc;

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

答案 1 :(得分:0)

您的第一个代码无效,因为您致电

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

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

要解决此问题,请将该代码放入viewDidLoad而不是init

相关问题