Reputation: 992
//taken from Core Data
var items:NSMutableArray = ["Item 1","Item 2","Item 1","Item 3"]
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if(editingStyle == .Delete){
let itemName = items.objectAtIndex(indexPath.row) as String
//delete all rows in core data with this item name
}
}
How to delete all rows in Core Data which have field name "itemName" ?
Upvotes: 0
Views: 3571
Reputation: 54
try this
if let index = find(items, items.objectAtIndex(indexPath.row))
{
items.removeAtIndex(index)
}
Upvotes: 1
Reputation: 23078
Create an NSFetchRequest
and set an NSPredicate
with your item name. Executing this fetch request gives you an array of all NSManagedObjects
with that predicate.
Then iterate over that array and call the NSManagedObjectContext
's method deleteObject(object)
let fetchRequest = NSFetchRequest(entityName: "yourEntityName")
fetchRequest.includesSubentities = false
fetchRequest.returnsObjectsAsFaults = false
fetchRequest.predicate = NSPredicate(format:"name == '\(itemName)'")
var error: NSError?
// moc is your NSManagedObjectContext here
items = moc.executeFetchRequest(fetchRequest, error: &error)!
for item in items {
moc.deleteObject(item)
}
Upvotes: 2