objective-c - iOS利用segue顺传的实现原理问题
大家讲道理
大家讲道理 2017-04-18 09:13:14
0
4
397

在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应该没有关系啊?为什么这样写是正确的呢?

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

全部回复(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构建的,不是你创建然后返回的。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板