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

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

大家讲道理
大家讲道理

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

reply all(4)
刘奇

This method creates a new object vc of the UIViewController class
There is no operation to create a new VC here, there is no memory allocation.

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

This code is exactly the same as the one below

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

Of course there is no need to return.

洪涛

If you don’t use segue to generate a vc from sb, it’s probably like this

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

segue calls destinationViewController, it actually does the same thing. It generates vc from sb and returns it to you
This vc is the same as what you generated yourself
{

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

}

present or push vc by segue
洪涛

vc is not newly created, it is just a pointer to the target viewcontroller, which is the viewcontroller to be jumped

左手右手慢动作
  • (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender This method is called when switching interfaces. At this time, the segue already contains the interface you want to go to, and is not created at this time. The storyboard will create the viewController object you want and give it to the segue.

UIViewController *vc = segue.destinationViewController;
vc.title = [NSString stringWithFormat:@"%@'s contact list",_accountField.text];
These two lines of code mean that you take out the target VC of the segue and modify it title.
The key point is to understand that the target VC you are going to is built by storybard, not something you create and then return.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template