Database Reference
In-Depth Information
Deleting objects from Core Data
Let's say you were too trigger-friendly and tapped the plus (+) button when you
didn't mean to. You didn't actually walk your dog, so you want to delete the walk
you just added.
You've added objects to Core Data, you've fetched them, modified them and saved
them again. What you haven't yet done is delete them—but you're about to do that
next.
First, add the following method to ViewController.swift :
func tableView(tableView: UITableView ,
canEditRowAtIndexPath indexPath: NSIndexPath ) -> Bool {
return true
}
You're going to use UITableView 's default behavior for deleting items: swipe left to
reveal the red Delete button, then tap on it to delete. The table view calls this
UITableViewDataSource method to ask if a particular cell is editable, and returning
true means all the cells should be editable.
Next, add the following method:
func tableView(tableView: UITableView ,
commitEditingStyle
editingStyle: UITableViewCellEditingStyle ,
forRowAtIndexPath indexPath: NSIndexPath ) {
if editingStyle == UITableViewCellEditingStyle . Delete {
//1
let walkToRemove =
currentDog . walks [indexPath. row ] as Walk
//2
let walks =
currentDog . walks . mutableCopy () as NSMutableOrderedSet
walks. removeObjectAtIndex (indexPath. row )
currentDog . walks = walks. copy () as NSOrderedSet
//3
managedContext . deleteObject (walkToRemove)
//4
var error: NSError ?
if ! managedContext . save (&error) {
 
Search WWH ::




Custom Search