从UITableView删除行并从Swift / iOS中的NSUserDefaults更新数组的正确方法

UITableView删除行并从NSUserDefaults更新数组的正确方法是什么?

在下面的例子中,我从NSUserDefaults读取一个数组,并提供一个UITableView的内容,我也允许用户删除UITableView项目,我不知道什么时候读取和写入到NSUserDefaults所以表一行删除后立即更新。 正如你所看到的,我首先读取viewDidLoad方法中的数组,并将其重新保存在commitEditingStyle方法中。 有了这个方法,当一行被删除时,我的表不会重新加载。

 override func viewDidLoad() { super.viewDidLoad() // Lets assume that an array already exists in NSUserdefaults. // Reading and filling array with content from NSUserDefaults. let userDefaults = NSUserDefaults.standardUserDefaults() var array:Array = userDefaults.objectForKey("myArrayKey") as? [String] ?? [String]() } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return array.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = UITableViewCell() cell.textLabel!.text = array[indexPath.row] return cell } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == UITableViewCellEditingStyle.Delete { array.removeAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) } // Save array to update NSUserDefaults let userDefaults = NSUserDefaults.standardUserDefaults() userDefaults.setObject(array, forKey: "myArrayKey") // Should I read from NSUserDefaults here right after saving and then reloadData()? } 

这通常如何处理?

谢谢

基本上它是正确的,但是如果有东西被删除,你应该只保存用户的默认值。

 if editingStyle == UITableViewCellEditingStyle.Delete { array.removeAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) let userDefaults = NSUserDefaults.standardUserDefaults() userDefaults.setObject(array, forKey: "myArrayKey") } 

读数组不需要,不build议使用。

cellForRowAtIndexPath重用单元格,您需要在Interface Builder中指定标识符。

 let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) 

数据源数组必须在类的顶层声明

 var array = [String]() 

然后在viewDidLoad分配值并重新加载表视图。

 override func viewDidLoad() { super.viewDidLoad() let userDefaults = NSUserDefaults.standardUserDefaults() guard let data = userDefaults.objectForKey("myArrayKey") as? [String] else { return } array = data tableView.reloadData() }