对象在 swift 中是 nil segue

Posted

技术标签:

【中文标题】对象在 swift 中是 nil segue【英文标题】:Object is nil segue in swift 【发布时间】:2021-09-27 12:22:30 【问题描述】:

我试图将一个对象从一个视图控制器传递到另一个视图控制器,但接收器收到 nil 并抛出一个错误说: 致命错误:在隐式展开可选值时意外发现 nil:文件

  override func prepare(for segue: UIStoryboardSegue, sender: Any?) 
        if segue.identifier == "sPropSegue" 
            if let indexPath = tableView.indexPathForSelectedRow 
                let prop = modelProperty.props[indexPath.row]
                
                let dVeiwController = segue.destination as? PDViewController
                
                detailVeiwController?.property = prop
                
                
            
        
    

UIViewController 中的代码

var property: Property!
    
    override func viewDidLoad() 
        super.viewDidLoad()
        
        propImage.image = UIImage(named: property.imageName)
        priceLable.text = property.price
        addressTextView.text = property.address        //propImage.image = UIImage()
        // Do any additional setup after loading the view.
    

请帮我解决这个问题。

提前谢谢你!

【问题讨论】:

是否调用了detailVeiwController?.property = prop?如何触发“segue”?通过代码?通过在 Storyboard 中从单元格连接到下一个视图控制器?如果是,则将其删除,然后从视图控制器执行到下一个,并在 didSelectRow 中调用performSegue() 我通过情节提要使用连接单元触发 您确定目标是 PDViewcontroller 吗?您是否将情节提要上的视图控制器属性设置为正确的类,好像这不会导致条件链接中的 nil 值? 【参考方案1】:

您需要确保从源 vc(不是表格单元格)到目标 vc 建立 segue,以便调用 override func prepare(for segue

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) 
   performSegue(withIdentifier:"sPropSegue",sender:nil)

【讨论】:

我尝试从 VC 建立 segue,但单元格点击甚至没有被触发。 设置表委托并在上面尝试【参考方案2】:

据我了解,您没有在 PDViewController 中获取属性对象。

所以尝试调试它。确保 prop 不为零。

在注释 viewDidLoad() 代码后尝试执行相同的代码。

还要确保您在尝试执行 segue 的控制器中有 self.table.delegate = self

【讨论】:

这将是一个更好的评论而不是一个答案,因为它是关于如何解决问题而不是解决问题的建议。

以上是关于对象在 swift 中是 nil segue的主要内容,如果未能解决你的问题,请参考以下文章

使用 Segue 在 Swift 中将带有数据的对象从一个视图传递到另一个视图

在 Swift 3 中使用 prepareForSegue 分配对象变为 nil

在 Swift 中,我如何避免选项和 nil 对象引用?

Realm Swift 返回所有 nil 值的对象

Swift Codable 将空 json 解码为 nil 或空对象

从 SCNNode 对象转场(Swift)