首页 > 解决方案 > 保存用户数据时索引超出范围 - Swift

问题描述

作为序言,我是编程和 Swift 的新手。

我正在学习教程并学习保存用户数据。只有启用了保存编码器/解码器功能时才会发生此崩溃。

这是编码和解码:

    override func encode(with coder: NSCoder) {
        coder.encode(clickCount, forKey: "clickCount")
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        clickCount = coder.decodeObject(forKey: "clickCount") as? [Int] ?? [Int]()
    }

我正在尝试在 clickCount 数组的 indexPath.row 处增加数组,以了解用户在我的 tableView 中单击单元格的次数

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if let vc = storyboard?.instantiateViewController(identifier: "Detail") as? DetailViewController {
            
            vc.selectedImage = pictures[indexPath.row]
            
            vc.totalPictures = pictures.count
            
            vc.selectedPictureNumber = (pictures.firstIndex(of: vc.selectedImage ?? "Error") ?? 0) + 1

            clickCount[indexPath.row] += 1
            
            navigationController?.pushViewController(vc, animated: true)
            
        }
        
    }

最后,这是 clickCount 数组

    var clickCount = [0,0,0,0,0,0,0,0,0,0]

需要明确的是,当我注释掉编码器和解码器功能时,递增数组按预期工作,但我想保存会话之间每行被点击的次数。

标签: arraysswiftindexpath

解决方案


推荐阅读