You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift视图控制器正向传值异常:emailCatched始终为nil

问题原因及解决方案:PasswordViewController获取emailCatched始终为nil

核心问题

你在EmailAddressViewController的continueButtonTapped方法里犯了一个关键错误:创建了PasswordViewController实例并给emailCatched赋值后,最终present的是一个全新的、未赋值的PasswordViewController实例,而非你已经传值的那个。

错误代码片段:

@objc private func continueButtonTapped() { 
    let email = emailField.text
    let vc = PasswordViewController()
    vc.emailCatched = email
    self.present(PasswordViewController(), animated: true) // 此处新建了未赋值的实例
}    

而你在VC2向VC3传值时逻辑正确:创建实例、完成赋值,再present这个已赋值的实例,所以能正常获取到值。

修复代码

将EmailAddressViewController中的present代码改为使用已赋值的vc实例:

@objc private func continueButtonTapped() { 
    let email = emailField.text
    let vc = PasswordViewController()
    vc.emailCatched = email
    self.present(vc, animated: true) // 改用已完成赋值的vc实例
}    

额外建议

PasswordViewController的viewDidLoad中使用print(emailCatched!)存在崩溃风险(当邮箱为空时),建议用可选绑定做安全处理:

override func viewDidLoad() {
    super.viewDidLoad()
    if let email = emailCatched {
        print(email)
    } else {
        print("邮箱为空")
    }
    // 其他视图加载代码...
}

内容的提问来源于stack exchange,提问作者user19534819

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 03:36:19