从 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 == .delete {
array.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .automatic)
let userDefaults = UserDefaults.standard
userDefaults.set(array, forKey: "myArrayKey")
}
不需要也不建议读回数组。
在cellForRowAtIndexPath
重用单元格时,需要在Interface Builder中指定标识符。
let cell = tableView.dequeueReusableCell(withIdentifier:"Cell", for: indexPath)
数据源数组必须在类的顶层声明
var array = [String]()
然后在viewDidLoad
中分配值并重新加载表格 View 。
override func viewDidLoad() {
super.viewDidLoad()
let userDefaults = UserDefaults.standard
guard let data = userDefaults.array(forKey: "myArrayKey") as? [String] else {
return
}
array = data
tableView.reloadData()
}
关于ios - 在 Swift/iOS 中从 UITableView 删除行并从 NSUserDefaults 更新数组的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39625350/