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
相关产品推荐
相关产品推荐

