Marc Durbach
Marc Durbach

Reputation: 31

error on adding element to NSMutableArray in Xcode 9 Beta 5

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

Answers (1)

vadian
vadian

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:

  • As mentioned in the comment use concrete type [String] rather than unrelated and unspecified NSMutableArray.
  • With the var keyword you get mutability for free.
  • Variable and method names start always with a lowercase letter.
  • Optional values which can be nil – like the text property –  are safely unwrapped.
  • The dedicated method stringArray of UserDefaults is used to avoid type casting.
  • UI elements passed in @IBAction are always objects (AnyObject). Whenever possible use the actual static type (e. g. UIButton)

Upvotes: 1

Related Questions