搜尋

首頁  >  問答  >  主體

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

大家讲道理大家讲道理2893 天前409

全部回覆(4)我來回復

  • 怪我咯

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

    這個方法新建了一個UIViewController類別的物件vc
    這裡哪有新建VC的操作啊,沒有任何記憶體分配啊。

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

    這程式碼就跟下面的是完全一樣的

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

    自然不需要返回。

    回覆
    0
  • PHP中文网

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

    如果不用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

    回覆
    0
  • PHP中文网

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

    vc不是新建的,只是一個指向目標viewcontroller的指針,就是要跳躍的那個viewcontroller

    回覆
    0
  • ringa_lee

    ringa_lee2017-04-18 09:15:14

    • (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建構的,不是你創建然後回來的。

    回覆
    0
  • 取消回覆