【发布时间】:2017-01-30 05:21:33
【问题描述】:
从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()?
}
这通常是如何处理的?
谢谢
【问题讨论】:
标签: ios arrays swift uitableview nsuserdefaults