Reputation: 31
I have a problem with the following code (i am learning swift right now) It happens when adding an element in line
items.addObjects(from: [TextField.text!])
The error message is :
2017-09-02 13:15:18.542629+0200 todolist[88230:154108272] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFArray insertObject:atIndex:]: mutating method sent to immutable object'
I am using XCcode 9 Beta 5
Here is the complete part of the code
@IBOutlet weak var TextField: UITextField!
@IBAction func Action(_ sender: Any) {
let itemsObject = UserDefaults.standard.object(forKey: "items")
var items:NSMutableArray = []
if let tempItems = itemsObject as? NSMutableArray {
items = tempItems
items.addObjects(from: [TextField.text!])
} else {
items = [TextField.text!]
}
UserDefaults.standard.set(items, forKey: "items")
TextField.text = ""
}
Upvotes: 1
Views: 99
Reputation: 285082
Your code contains a lot of issues, this is a safe native Swift version:
@IBOutlet weak var textField: UITextField!
@IBAction func action(_ sender: AnyObject) {
guard let textToAppend = textField.text else { return }
var items : [String]
if let itemsObject = UserDefaults.standard.stringArray(forKey: "items") {
items = itemsObject
} else {
items = [String]()
}
items.append(textToAppend)
UserDefaults.standard.set(items, forKey: "items")
textField.text = ""
}
Please note:
[String]
rather than unrelated and unspecified NSMutableArray
.var
keyword you get mutability for free. nil
– like the text
property – are safely unwrapped.stringArray
of UserDefaults
is used to avoid type casting.@IBAction
are always objects (AnyObject
). Whenever possible use the actual static type (e. g. UIButton
)Upvotes: 1