gpt4 book ai didi

ios - 可选链接与可选绑定(bind) : When to use which?

转载 作者:搜寻专家 更新时间:2023-10-31 22:13:15 24 4
gpt4 key购买 nike

在寻找刷新 UINavigationBar 的正确方法时(参见:How to properly refresh a UINavigationBar?)我遇到了这个问题:

这会按预期刷新 UINavigationBar,即使不是以干净的方式:

if let navigationController = self.navigationController {
navigationController.popViewControllerAnimated(false)
navigationController.pushViewController(self, animated: false)
}

但是,这会弹出当前 View Controller ,但不会推送它:

navigationController?.popViewControllerAnimated(false)
navigationController?.pushViewController(self, animated: false)

如何解释这种行为?

最佳答案

可选绑定(bind)将您要绑定(bind)的内容存储在变量中。在本例中,它是 navigationController

另一方面,可选链接不会将左侧的值放入变量中。它只是说

I will check whether this value on the left of the question mark is nil. If it isn't, evaluate the rest of the expression. If it is, evaluate to nil

因此,在弹出 View Controller (第一行)之后,self.navigationController 变为 nil,因此不会评估第二行中的方法调用。

你可能有这些困惑:

Why does self.navigationController become nil?

一种可能是selfnavigationController的顶层 View Controller 。 self 弹出后,它不属于任何导航 Controller 。

Why does optional binding work but not optional chaining?

正如我之前所说,可选绑定(bind)将 self.navigationController 的值放入变量 navigationController 中。因此,即使 self.navigationController 为 nil,navigationController 仍保持其值。

关于ios - 可选链接与可选绑定(bind) : When to use which?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39066194/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com