UITableView
から行を削除し、NSUserDefaultsから配列を更新する適切な方法はありますか?Swift/iOSのNSUserDefaultsからUITableViewと配列を更新する適切な方法
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()?
}
これは通常どのように処理されますか?
おかげ
ありがとうございました! –