Delete Data from Coredata Swift
Update on my coding issue with executing a delete of data in swift and coredata. This the code I ended up with that worked.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
switch editingStyle {
case .Delete:
// remove the deleted item from the model
let appDel:AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let context:NSManagedObjectContext = appDel.managedObjectContext!
context.deleteObject(myData[indexPath.row] as NSManagedObject)
myData.removeAtIndex(indexPath.row)
context.save(nil)
//tableView.reloadData()
// remove the deleted item from the `UITableView`
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
default:
return
}
}
EDIT Above for Swift 2.2 and Xcode 7.3.1
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
switch editingStyle {
case .Delete:
// remove the deleted item from the model
let appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context:NSManagedObjectContext = appDel.managedObjectContext
context.deleteObject(myData[indexPath.row] )
myData.removeAtIndex(indexPath.row)
do {
try context.save()
} catch _ {
}
// remove the deleted item from the `UITableView`
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
default:
return
}
}
Also need was these two lines of code to be corrected.
var myData: Array<AnyObject> = []
let managedObjectContext = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext
how to delete particular record in coredata using Swift?
Don't use a custom class. Use only the provided User
class.
First of all declare a data source array (replacing displayDatasssss
)
var users = [User]()
In the tap
method load the data and insert new items in the Core Data stack. Consider that each tap on the button inserts duplicate items into the database. Older entries are not removed.
As User
has only name
and id
properties email
is assigned to id
.
The items are appended to the data source array and saved in the context.
@IBAction func tap(_ sender: Any) {
let url = "http://jsonplaceholder.typicode.com/users")!
let task = session.dataTask(with: url){ [unowned self] (data, response,error)in
if let error = error { print(error); return }
do {
// Array of Data
let fetchData = try JSONSerialization.jsonObject(with: data!) as! [[String:Any]]
for eachDataItem in fetchData {
let name = eachdataitem["name"] as! String
let email = eachdataitem["email"] as! String
let newUser = User(context: self.context)
newUser.name = name
newUser.id = email
self.users.append(newUser)
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
try self.context.save()
} catch{
print("Error 2", error)
}
}
task.resume()
}
In viewDidLoad
fetch the data from CoreData
and reload the table view
override func viewDidLoad() {
super.viewDidLoad()
do {
let request : NSFetchRequest<User> = User.fetchRequest()
users = try context.fetch(request)
tableView.reloadData()
} catch { print(error) }
}
In cellForRow
assign the property value(s) to the labels, nothing else
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell1") as! TableViewCell1
let user = users[indexPath.row]
cell.label.text = user.name
return cell
}
The delete method is quite similar to yours
let deleteAction = UITableViewRowAction(style: .default, title: "Delete", handler: { [unowned self] (action, indexPath) in
print("Delete tapped")
// remove the deleted item from the model
let objectToDelete = self.users.remove(at: indexPath.row)
self.context.delete(objectToDelete)
do {
try self.context.save()
self.tableView.deleteRows(at: [indexPath], with: .automatic)
} catch {
print(error)
}
}
return [editAction, deleteAction]
Note: Print always errors, don't ignore them or print only meaningless literal strings
how to delete row from coredata (Entity) ios swift
Try Like this,
func buttonDeletePressed(sender:UIButton) {
let appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context:NSManagedObjectContext = appDel.managedObjectContext
let index = sender.tag
context.deleteObject(people[index] as NSManagedObject)
people.removeAtIndex(index)
let _ : NSError! = nil
do {
try context.save()
self.tableView.reloadData()
} catch {
print("error : \(error)")
}
}
Hope this will help you.
Deleting from Core Data Swift 4
In coredata every object should have Id if you want to delete it , like this
let fetchRequest: NSFetchRequest<Favorite> = Favorite.fetchRequest()
fetchRequest.predicate = Predicate.init(format: "FavoriteID==\(ID)")
do {
let objects = try context.fetch(fetchRequest)
for object in objects {
context.delete(object)
}
try context.save()
} catch _ {
// error handling
}
iOS: Delete ALL Core Data Swift
I have got it working using the following method:
@IBAction func btnDelTask_Click(sender: UIButton){
let appDel: foodforteethAppDelegate = UIApplication.sharedApplication().delegate as foodforteethAppDelegate
let context: NSManagedObjectContext = appDel.managedObjectContext
let request = NSFetchRequest(entityName: "Food")
myList = context.executeFetchRequest(request, error: nil)
if let tv = tblTasks {
var bas: NSManagedObject!
for bas: AnyObject in myList
{
context.deleteObject(bas as NSManagedObject)
}
myList.removeAll(keepCapacity: false)
tv.reloadData()
context.save(nil)
}
}
However, I am unsure whether this is the best way to go about doing it. I'm also receiving a 'constant 'bas' inferred to have anyobject' error - so if there are any solutions for that then it would be great
EDIT
Fixed by changing to bas: AnyObject
Delete data from CoreData
The IndexSet
method works when you are using onDelete
with a ForEach
loop.
Since you don't have access to the IndexSet
with a Button
you pass the actual item.
Change your function to this.
public func deleteTodo(todoDB: TodoDB){
managedObjectContext.delete(todoDB)
do{
try managedObjectContext.save()
} catch{
print(error)
}
}
And put this code within the trash button's action like this.
deleteTodo(todoDB: todoDB)
Swift 3: How to delete the single record in the Core Data when a UIbutton is Pressed
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "FavProfile")
let predicate = NSPredicate(format: "profileID == %@", id as CVarArg)
fetchRequest.predicate = predicate
let moc = getContext()
let result = try? moc.fetch(fetchRequest)
let resultData = result as! [FavProfile]
for object in resultData {
moc.delete(object)
}
do {
try moc.save()
print("saved!")
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
}
use predicate for profileID.
Delete a record from an Entity in core data
If you are trying to delete item with specific index, i have provided solution for deleting item at index (this might cause array out of bound exception), but i recommend to use predicate, lets say that may be id, name of item that you are willing to delete.
I am providing solution with perception from your question,
You can use process of fetching entity from DB and delete that particular item you want to remove.
Please manage to add following code, Do not forgot to use predicate if you want to delete some particular item
func deleteCoreData(rowIndex: Int) {
let managedContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
do{
//1. Create Request
let request: NSFetchRequest<PlayListDetails> = PlayListDetails.fetchRequest()
//Predicate is optional as per need
//let predicate = NSPredicate(format: "playlistId = %@", id)
//request.predicate = predicate
//2. Result object
let results = try managedObjectcontext.fetch(request as! NSFetchRequest<NSFetchRequestResult>)
guard results.count > 0 else {
print("No tems available handle error")
return
}
for i in 0...results.count-1 {
if i == rowIndex {
let theItem = results[index] as NSManagedObject
managedObjectcontext.delete(item)
}
}
/*
for item in results as! [NSManagedObject]{
print(item)
//hit delete for item you want
managedObjectcontext.delete(item)
} */
do {
try managedObjectcontext.save() // <- remember to put this :)
} catch {
// Do something... fatalerror
print("handle error")
return
}
} catch{
print(error)
print("handle error")
return
}
print("handle error")
}
Update
"This is the query i wants to execute sir.. Delete all from PlayListDetails where trackId=123 and playlistName= demo How would I achieve this in above code"
Using predicate
//use predicate for single predicate and compound for multiple predicate
//Predicate is optional as per need
let predicate = NSPredicate(format: "trackId = %@", id)
let predicate2 = NSPredicate(format: "name = %@", "some name")
//let compoundPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [predicate, predicate2])
request.predicate = predicate
on delete section use
for item in results as! [NSManagedObject]{
print(item)
//hit delete for item you want
managedObjectcontext.delete(item)
}
Related Topics
Is Swiftui Backwards-Compatible With iOS 12.X and Older
Swift3 Optionals Chaining in If Conditions Bug
How to Get User Home Directory Path (Users/"User Name") Without Knowing the Username in Swift3
How to Make the Scroll of a Tableview Inside Scrollview Behave Naturally
Show Am/Pm in Capitals in Swift
Swift: Determine What Object Called a Function
Different Ways to Initialize a Dictionary in Swift
Function Does Not Wait Until the Data Is Downloaded
Retrieve Only 5 Users At a Time :Firebase [Like Instagram]
Compile Error in Swift 4 on Parameter Passing
Lesser Than or Greater Than in Swift Switch Statement
How to Check If a Property Value Exists in Array of Objects in Swift
Nsimage to Nsdata as Png Swift
Why Does Implicitly Unwrapped Optional Not Unwrap in Dictionary of Type [String:Any]