iOS利用segue顺传的实现原理问题

在iOS简单通讯录的教程中,从登录界面到通讯录联系人界面的数据顺传部分的方法如下,根据不同的登录用户名,变换通讯录联系人界面的标题:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
  UIViewController *vc = segue.destinationViewController;
  vc.title = [NSString stringWithFormat:@"%@的联系人列表",_accountField.text];
}

我的理解是:这个方法新建了一个UIViewController类的对象vc,并把seguedestinationViewController赋值给了vc,然后改变了vc对象的title,最后也没有返回vc,和destinationViewControllertitle应该没有关系啊?为什么这样写是正确的呢?

阅读 3.2k
4 个回答

这个方法新建了一个UIViewController类的对象vc
这里哪有新建VC的操作啊,没有任何内存分配啊。

UIViewController *vc = segue.destinationViewController;
vc.title = [NSString stringWithFormat:@"%@的联系人列表",_accountField.text];

这代码就和下面的是完全一样的

segue.destinationViewController.title = [NSString stringWithFormat:@"%@的联系人列表",_accountField.text];

自然不需要返回。

如果不用segue 从sb生成一个vc大概是这样

UIStoryboard *sb = [UIStoryboard storyboardWithName:@"your sb name" bundle:nil];
UIViewController *vc = [sb instantiateViewControllerWithIdentifier:@"your vc identifier"];
vc.title = @"your title";
...
present or push vc

segue去调用destinationViewController时 其实做的也是这个事情 它从sb生成vc 然后返回给你
这个vc和你自己生成是一样的
{

vc.title = @"your title";
...

}

present or push vc by segue

vc不是新建的,只是一个指向目标viewcontroller的指针,就是要跳转的那个viewcontroller

  • (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender这个方法是在切换界面的时候调用,这个时候segue就已经包含了你要去的界面了,并非这个时候创建的。storyboard会自己创建你要去的viewController对象,并把它给segue。

UIViewController *vc = segue.destinationViewController;
vc.title = [NSString stringWithFormat:@"%@的联系人列表",_accountField.text];
这两句代码是你把segue的目标VC取出,修改了它的title。
重点是理解你要去的目标VC是storybard构建的,不是你创建然后返回的。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题