user1519226
user1519226

Reputation: 77

NSUserDefaults arrayForKey value of anyObject has no member removeAtIndex (Swift)

I am using the NSUserDefaults to store an array (of strings), and when loading it, it appears to be interpreted as an AnyObject instead of an Array. I don't understand how this is possible because I am using the arrayForKey method for my default, which I thought was supposed to return an array?

The exact error I am getting is:

Value of type '[AnyObject]?' has no member 'removeAtIndex'

which is occurring at shoppingListDefaults.arrayForKey("ShoppingList").removeAtIndex(indexPath.row)

let shoppingListDefaults = NSUserDefaults.standardUserDefaults()
let deleteAction = UITableViewRowAction(style: .Normal, title: "Delete") { (rowAction:UITableViewRowAction, indexPath:NSIndexPath) -> Void in
        shoppingListDefaults.arrayForKey("ShoppingList").removeAtIndex(indexPath.row)
        self.slItems.reloadData()   // `slItems` is the IBOutlet for a UITableView
    }
deleteAction.backgroundColor = UIColor.redColor()
return [deleteAction]

Upvotes: 0

Views: 308

Answers (2)

dan
dan

Reputation: 9825

arrayForKey returns an optional, so you have to unwrap it before you can call anything else on it. You also can't directly edit the array you get from defaults since it is immutable. You have to edit the array and then update defaults with the update array.

Try:

if var list = shoppingListDefaults.arrayForKey("ShoppingList") {
    list.removeAtIndex(indexPath.row)
    shoppingListDefaults.setArray(list, forKey: "ShoppingList")
}

Upvotes: 1

Kubba
Kubba

Reputation: 3438

This array is immutable. You need to retrieve it from defaults, remove object, and set back modified array to defaults.

Upvotes: 0

Related Questions