unwind segue和delegation的区别

Posted

技术标签:

【中文标题】unwind segue和delegation的区别【英文标题】:Difference between unwind segue and delegation 【发布时间】:2014-05-13 14:07:21 【问题描述】:

我想知道是否有人可以在下面的示例中解释使用 unwind segue 和使用委托之间的区别:

我有一个FriendsTableViewController 由朋友的array 填充,另一个AddFriendTableViewController 具有将friend 添加到FriendsTableViewController 的功能。

这就是我使用unwind segueAddFriendViewController 发送数据的方式:

#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender

    // Check whether the Done button was tapped.
    // If it wasn’t, instead of saving the friend, the method returns without doing anything else.
    if (sender != self.doneButton) return;

    // See whether there’s text in the text field.
    if (self.nameTextField.text.length > 0) 
        // If there’s text, create a new friend and give it's properties the input from the text fields.
        self.friend = [[Friend alloc] initWithName:self.nameTextField.text
                                          dateOfBirth:self.birthdayDatePicker.date
                                        numberOfGifts:0];
    

这就是我使用unwind segue actionAddFriendTableViewController 中的数据添加到FriendsTableViewController 中的array 的方法:

#pragma mark - Actions

- (IBAction)unwindSegue:(UIStoryboardSegue *)segue

    // Retrieve the source view controller, the controller that is unwinding from.
    AddFriendTableViewController *soruce = [segue sourceViewController];

    // Retrieve the soruce view controller’s friend object.
    Friend *friend = soruce.friend;

    // See whether the item exists.
    // If it’s nil, either the Cancel button closed the screen or the text field had no text, so you don’t want to save the item.
    if (friend != nil) 
        // If it does exist, add the item to the friends array.
        [self.friends addObject:friend];

        // Reload the data in the table.
        [self.tableView reloadData];
    

现在这可以按我的意愿工作,所以我希望我没有违反任何 *** 规则或冒犯任何人,但我只是想知道我的示例代码的使用方式与是否进行了相同的场景之间有什么区别,但是使用AddFriendViewController 的自定义委托方法。如果有人能解释就太好了!

【问题讨论】:

【参考方案1】:

使用 unwind segue 与使用委托非常相似,具有以下优点:

您无需实现任何关闭逻辑 您不需要在导航堆栈上下传递引用 您无需声明委托协议 放松应用中的多个阶段很简单

缺点是

依赖于使用情节提要(这可能会妨碍可重用性) 如果它们很多,可能会导致与 prepareForSegue 相同的混乱,其中包含大量分支标识符名称 如果您决定通过其他方法(而不是 segue)呈现视图控制器,那么您将无法从中放松

您的代码看起来不错。我会坚持下去的。

【讨论】:

非常感谢您对此的解释,并感谢您提供彻底而详细的回答!我会将此标记为已接受,因为我现在在使用 unwind segue 时既有优点也有缺点 :) +1 表示最后一个。 “如果您决定通过其他方法(而不是 segue)呈现视图控制器,那么您将无法从中放松”。我几乎被卖掉了,但这在我看来是一个交易破坏者。协议/委托模式保持视图控制器自包含和可移植,因此,我相信这是更好的选择。 是的,我也同意这一点,但在我正在实施的项目中,使用“unwind segue way”的项目非常小,我觉得这种方法对于项目来说已经足够了!跨度> 展开 segue 是否存在内存管理问题?展开 segue 是否像协议中的委托一样使用弱引用???如果有人知道,请给我答案。 @NiteshBorad 不,没有内存管理问题。如果您有特定的想法,请提出一个新问题。

以上是关于unwind segue和delegation的区别的主要内容,如果未能解决你的问题,请参考以下文章

确定 unwind segue 动画何时完成

使用带有情节提要参考的“Unwind Segue”时“没有标识符的segue”

Unwind Segue - 将出口拖到哪里?

使用 unwind segues 推送数据

不同的 Unwind Segue 取决于来源

iOS从推送segue中检测unwind segue