'Delete rows from UITableView and update array from NSUserDefaults
With the tableview I am trying to delete only one record of the list but with my code it deletes all the userDefault data. how do i delete only one record?
cell.buttonPressed = {
self.recDictionaryId?["\(title)"] = "\(sentence)"
self.pokemonArray.remove(at: indexPath.row)
self.tvPokemon.deleteRows(at: [indexPath], with: .automatic)
let defaults = UserDefaults.standard
defaults.set(self.pokemonArray, forKey: "UserDefSaveDictionary")
defaults.synchronize()
self.tvPokemon.reloadData()
}
I also tried with:
removeObject(forKey: "UserDefSaveDictionary")
but the result is the same
Solution 1:[1]
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
objects.remove(at: indexPath.row)
self. deleteItem(indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
}
}
func deleteItem(_ index: Int) {
let userDefaults = UserDefaults.standard
if let data = userDefaults.data(forKey:”keyName”) , var array = try? JSONDecoder().decode([Model].self, from: data) {
array.remove(at: index)
guard let result = try? JSONEncoder().encode(array) else { return }
userDefaults.set(result, forKey:”keyName”)
}
}
you have to fetch the UserDefaults response array and convert it to a model then it would be much easier, if you want make this better you can try by adding a completion block to deleteItem() function and inside that you can perform real deletion
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jok3r |
