ViewDidLoad之前的InitWithName执行可能吗?

时间:2013-03-25 16:31:12

标签: iphone objective-c viewcontroller viewdidload

我试图在两个视图控制器之间移动一个NSString,在搜索了所有复杂的方法之后,我想要习惯的最简单,最直接的方法是在接收VC中编写一个initWithName函数。在发送VC中调用它。它确实成功地移动了它但是我希望它在ViewDidLoad加载textViewer之前执行,以便在按下Tab键后立即显示它。这是来自发送VC的代码:

- (void)textViewDidEndEditing:(UITextView *)textView
{   
    if ([textView.text isEqualToString: @""]) {
        textView.text = @"*Paste the machine code in question here*";
    }
    SecondViewController *theVCMover = [[SecondViewController alloc] initWithName: textView.text];
    [self.navigationController pushViewController:theVCMover animated:YES]; //Is this really necessary if I'm not going to segue it directly, I'm just waiting for the user to press the next tab
    gotItLabel.text = @"Got it! Ready for action...";
}

以下是接收VC上的代码:

 - (id)initWithName:(NSString *)theVCMovee {
    self = [super initWithNibName:@"SecondViewController" bundle:nil];
    if (self) {
        rawUserInput = theVCMovee;
        CleanerText.text = rawUserInput;
    }
    return self;
} 
- (void)viewDidLoad {
        [super viewDidLoad];
    CleanerText.text = rawUserInput;
        NSLog(@"Got the other tab's text and it's %@ ", rawUserInput);

}

2 个答案:

答案 0 :(得分:1)

您的代码大多数都很好,但您会发现,由于您拥有更复杂的视图控制器,因此您不一定要编写自定义初始化程序来执行每一项属性设置。请注意,如果CleanerText是您从笔尖加载的UI元素,则无法在init方法中设置CleanerText.text - 在调用-viewDidLoad之前不会加载它。

但是,如果声明rawUserInput的属性或要设置的其他变量,则不必在init中执行所有操作。然后你可以去:

SecondViewController *theVCMover = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil];
theVCMover.rawUserInput = textView.text;
theVCMover.otherProperty = otherValue;
....

其余的代码也是一样的。

答案 1 :(得分:0)

init完成执行之前,您无法(可靠地)调用实例上的方法,因此这种模式是“安全的”,并且它应该如何工作。