准备转场时致命错误索引超出范围

Posted

技术标签:

【中文标题】准备转场时致命错误索引超出范围【英文标题】:Fatal error index out of range when preparing for segue 【发布时间】:2020-10-01 16:25:01 【问题描述】:

每两次我执行“openChat”转场,我得到错误致命错误:在这部分准备转场时索引超出范围:

chatThread[((tableView.indexPathForSelectedRow as NSIndexPath?)?.row)!]

chatThread 是对 ChatThread 结构的引用。我这样初始化它:var chatThread = [ChatThread]()

代码

override func prepare(for segue: UIStoryboardSegue, sender: Any?) 
    if segue.identifier == "openChat" 
        if let destination = segue.destination as? Conversation 
            print("opening conversation")
            print(destination)
            print("destinationThread")
            print(destination.chatThread)
            print("currentThread")
            print(chatThread[((tableView.indexPathForSelectedRow as NSIndexPath?)?.row)!])
            destination.chatThread = chatThread[((tableView.indexPathForSelectedRow as NSIndexPath?)?.row)!]
        
    

表格视图代码

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) 
    let users = [PFUser.current()!.username!, self.friendStruct[indexPath.row].username!] as NSArray
    let query = PFQuery(className: "ChatThread")
    query.whereKey("users", containsAllObjectsIn: [users])
    query.getFirstObjectInBackground(block: (object, error) -> Void in
        print("Found \(object)")
        if object != nil 
            // These users already have a thread
            let threadId = object!.objectId!
            let lockedBy = object!["lockedBy"] as? String
            let lastSender = object!["lastSender"] as! String
            let updatedAt = object!.updatedAt!
            self.chatThread.append(ChatThread(threadId: threadId, lockedBy: lockedBy, users: users, lastSender: lastSender, updatedAt: updatedAt.timeAgoDisplay2(), otherUser: self.friendStruct[indexPath.row].username!, existingConversation: true))
            DispatchQueue.main.async 
                if self.shouldPerformSegue(withIdentifier: "openChat", sender: self)
                    self.performSegue(withIdentifier: "openChat", sender: self)
                
            
        else
            // Users never spoke
            print("users never spoke")
            DispatchQueue.main.async 
                self.chatThread.append(ChatThread(threadId: nil, lockedBy: nil, users: users, lastSender: nil, updatedAt: nil, otherUser: self.friendStruct[indexPath.row].username!, existingConversation: false))
                DispatchQueue.main.async 
                    if self.shouldPerformSegue(withIdentifier: "openChat", sender: self)
                        self.performSegue(withIdentifier: "openChat", sender: self)
                    
                
            
        
    )

【问题讨论】:

你可以为你的tableView函数添加代码吗? 刚刚添加@rs7 能否同时添加 cellForRow、numberOfRows、numberOfSections(如果适用) chatThread struct 仅在选择单元格时更新,因此在 cellForRow、numberOfRows 和 numberOfSections 中没有引用它 我不确定您的问题是什么,因为我缺少一些信息。但是根据您提供给我的内容,我会将显示错误的行(在 prepareForSegue 内)更改为:destination.chatThread = chatThread.last。原因是,您在 performSegue 之前将线程附加到 chatThread 数组,所以数组的最后一个元素就是您要传入的元素。 【参考方案1】:

来自@rs7 的解决方案。只需将chatThread[((tableView.indexPathForSelectedRow as NSIndexPath?)?.row)!] 更改为chatThread.last 即可解决问题。

工作代码

override func prepare(for segue: UIStoryboardSegue, sender: Any?) 
    if segue.identifier == "openChat" 
        if let destination = segue.destination as? Conversation 
            destination.chatThread = chatThread.last
        
    

【讨论】:

以上是关于准备转场时致命错误索引超出范围的主要内容,如果未能解决你的问题,请参考以下文章

致命错误:数组索引超出范围。刷新时迅速

Swift 致命错误:数组索引超出范围

Swift 致命错误:数组索引超出范围

致命错误:在特定视图上刷新数据时索引超出范围

致命错误:将 FirebaseData 传递给 tablviewCell 时,索引超出范围

(Swift) 致命错误:索引超出范围