线程 1:向不可变对象发送信号 SIGABRT 变异方法'

Thread 1: signal SIGABRT mutating method sent to immutable object'

我是 Swift 编程新手,一直在开发 To-Do List 应用程序。我正在尝试使用永久数据存储来保存用户输入的信息,但我不断收到错误 "Thread 1: signal SIGABRT "。当我检查输出日志时,我看到错误

"Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFArray insertObject:atIndex:]: mutating method sent to immutable object'"

我的代码如下。我使用一个简单的文本框和一个按钮:

@IBOutlet var text1: UITextField!

@IBAction func button1(_ sender: AnyObject) {

    let listObject = UserDefaults.standard.object(forKey: "lists")

    var items:NSMutableArray

   if let tempitems = listObject as? NSMutableArray {

        items = tempitems

      items.addObjects(from: [text1.text!])

  } else {

        items = [text1.text!]

    }

    UserDefaults.standard.set(items, forKey: "lists")

    text1.text = ""

}

崩溃正是它的意思:你不能改变一个不可变的对象。试试这个:

var items: NSMutableArray!

if let listObject = UserDefaults.standard.object(forKey: "lists") as? NSArray {
    items = listObject.mutableCopy() as! NSMutableArray
} else {
    items = NSMutableArray()
}

items.addObjects(from: [text1.text!])