search

Home  >  Q&A  >  body text

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

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

1

2

3

4

<code class="objc">- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{

  UIViewController *vc = segue.destinationViewController;

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

}</code>

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

大家讲道理大家讲道理2892 days ago402

reply all(4)I'll reply

  • 怪我咯

    怪我咯2017-04-18 09:15:14

    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.

    1

    2

    <code>UIViewController *vc = segue.destinationViewController;

    vc.title = [NSString stringWithFormat:@"%@的联系人列表",_accountField.text];</code>

    This code is exactly the same as the one below

    1

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

    Of course there is no need to return.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 09:15:14

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

    1

    2

    3

    4

    5

    6

    <code>UIStoryboard *sb = [UIStoryboard storyboardWithName:@"your sb name" bundle:nil];

    UIViewController *vc = [sb instantiateViewControllerWithIdentifier:@"your vc identifier"];

    vc.title = @"your title";

    ...

    present or push vc

    </code>

    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
    {

    1

    2

    <code>vc.title = @"your title";

    ...</code>

    }

    1

    <code>present or push vc by segue</code>

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 09:15:14

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

    reply
    0
  • ringa_lee

    ringa_lee2017-04-18 09:15:14

    • (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.

    reply
    0
  • Cancelreply