我想从表格视图和核心数据中删除一个单元格。当我尝试删除单元格时,将其从表视图中删除,但不从核心数据中删除,如果更新表视图,则再次出现。我试图在删除操作中使用更新表视图,但是它不起作用。也许我应该尝试ManagedObjectContext,但是它对我不起作用,因为出现错误。
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let nib = UINib.init(nibName: "CustomTableViewCell", bundle: nil)
self.tableView.register(nib, forCellReuseIdentifier: "cell")
let fetchRequest: NSFetchRequest<Person> = Person.fetchRequest()
do {
let desserts = try PersistenceServce.context.fetch(fetchRequest)
self.desserts = desserts
self.tableView.reloadData()
} catch {}
}
@IBOutlet weak var tableView: UITableView!
var desserts = [Person]()
@IBAction func onAddTapped() {
let alert = UIAlertController(title: "Add Goal", message: nil, preferredStyle: .alert)
alert.addTextField { (dessertTF) in
dessertTF.placeholder = "Enter Goal"
}
let action = UIAlertAction(title: "Add", style: .default) { (_) in
guard let dessert = alert.textFields?.first?.text else { return }
print(dessert)
let person = Person(context: PersistenceServce.context)
PersistenceServce.saveContext()
self.desserts.append(person)
self.tableView.reloadData()
}
alert.addAction(action)
present(alert, animated: true)
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
performSegue(withIdentifier: "segue", sender: self)
}
}
extension ViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return desserts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let dessert = desserts[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
guard editingStyle == .delete else { return }
desserts.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .automatic)
}