2016-08-29 31 views
0

我正在使用NSUserDefaults來存儲一個數組(字符串),並且在加載它時,它似乎被解釋爲一個AnyObject而不是一個數組。我不明白這是如何可能的,因爲我使用arrayForKey方法爲我的默認,我認爲應該返回一個數組?NSUserDefaults anyForObject的arrayForKey值沒有成員removeAtIndex(Swift)

我得到確切的錯誤是:

型的價值「[AnyObject]?沒有成員 'removeAtIndex'

其在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] 

回答

0

發生該數組是不可變的。您需要從默認值中檢索它,刪除對象,並將修改後的數組設置爲默認值。

1

arrayForKey返回一個可選項,所以你必須打開它才能調用其他任何東西。你也不能直接編輯你從默認獲得的數組,因爲它是不可變的。您必須編輯數組,然後使用更新數組更新默認值。

嘗試:

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