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
}
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)
How to delete all data from core data when persistentContainer is not in App delegate method in swift
One of the solutions can be to use NSBatchDeleteRequest
for all entities in the persistentContainer. You can add these methods to your CoreDataStack
:
func deleteAllEntities() {
let entities = persistentContainer.managedObjectModel.entities
for entity in entities {
delete(entityName: entity.name!)
}
}
func delete(entityName: String) {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
do {
try persistentContainer.viewContext.execute(deleteRequest)
} catch let error as NSError {
debugPrint(error)
}
}
The whole code can be found here
Deleting a table view row with Swift 3 and CoreData
When you delete data in coreData it wont be saved by coreData unless you save the action. The delete action should be like this..
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
managedObjectContext.delete(sessions[indexPath.row])
do {
try managedObjectContext.save()
tableView.reloadData()
} catch let error as NSError {
print("Could not save. \(error), \(error.userInfo)")
}
}
}
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
Related Topics
What's Happening Behind the Scenes in Xctest's @Testable
How to Make a Popup Window with an Image Swift
Removing a View Controller from Memory When Instantiating a New View Controller
Swift - Using Cgcontext to Draw with Finger
Automatically Change Cell Height Based on Content - Swift
How to Get All Keys and Values into Separate String Arrays from Nsdictionary in Swift
Swiftui - Optional Timer, Reset and Recreate
How to Run an iOS Application Every 1 Minute Infinitely
Share Attachment from Mail App with Share Extension in iOS
iOS Swift. How to Get a Gps Metadata from Just a Uiimage (Nsurl)
Infinite Scroll on iOS with Swift
Swift, Parse.Com: How to Pass Data from Query