[__NSCFArray insertObject:atIndex:]: 发送到不可变对象的突变方法', 线程: SIGABRT



我正在构建一个待办事项应用程序。当我按"添加任务"按钮时,我的应用程序会崩溃并给我以下错误:

[__ nscfarray insertobject:atindex:]:发送到不变对象的突变方法'

它还将我返回到线程Sigabrt错误。任何帮助将不胜感激。

这是我的SecondViewController

class SecondViewController: UIViewController, UITextFieldDelegate {
    @IBOutlet weak var taskValue: UITextField!
    @IBAction func addTask(_ sender: Any) {
        let itemsObject = UserDefaults.standard.object(forKey: "items")
        var items:NSMutableArray!
        if let tempItems = itemsObject as? NSMutableArray{
            items = tempItems
            items.addObjects(from: [taskValue.text!])
        } else{
            items = [taskValue.text!]
        }
        UserDefaults.standard.set(items, forKey: "items")
        taskValue.text = ""
    }
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
}

我的第一个视图控制器在这里:

class FirstViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{
    var items: NSMutableArray = []
    //table view
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellContent = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "Cell")
        var cellLabel = ""
        if let tempLabel = items[indexPath.row] as? String{
            cellLabel = tempLabel
        }
        cellContent.textLabel?.text = cellLabel
        return cellContent
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        let itemsObject = UserDefaults.standard.object(forKey: "items")
        if let tempItems = itemsObject as? NSMutableArray{
            items = tempItems
        }
    }
}

发生错误是因为您无法将Swift数组投射到NSMutableArray。不要在Swift中使用NSMutable...基础类型。

在Swift中,只需使用var关键字。

很容易获得可变的对象。

UserDefaults有一个专门的方法来获取字符串数组。

@IBAction func addTask(_ sender: Any) {
    var items : [String]
    if let itemsObject = UserDefaults.standard.stringArray(forKey: "items") {
        items = itemsObject
        items.append(taskValue.text!) // it's pointless to use the API to append an array.
    } else{
        items = [taskValue.text!]
    }
    UserDefaults.standard.set(items, forKey: "items")
    taskValue.text = ""
}

最新更新