简体   繁体   中英

how to delete particular record in coredata using Swift?

my scenario, I am loading JSON Data into CoreData, after that I am fetching into Tableview. Now, Each and every tableview cell have swipe with Delete and Edit button. If I click delete I need to remove data from coredata and tableview both place.

My JSON Structure

   class displyDataClass {
    var name : String
    var username : String
    var email : String

init(name : String,username : String,email :String) {
    self.name = name
    self.username = username
    self.email = email
   }
}

JSON Load Into CoreData

import UIKit
import CoreData

class ViewController: UIViewController ,UITableViewDelegate,UITableViewDataSource{

var displayDatasssss = [displyDataClass]()
var context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

@IBOutlet weak var tableView: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()
    print("hai")

    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return displayDatasssss.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell1") as! TableViewCell1





    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "User")
    cell.label.text = displayDatasssss[indexPath.row].email


    let _:AppDelegate = (UIApplication.shared.delegate as! AppDelegate)
    let context:NSManagedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    let newUser = NSEntityDescription.insertNewObject(forEntityName: "User", into: context) as NSManagedObject
    newUser.setValue(cell.label.text, forKey: "name")

    do {
        try context.save()
    } catch {}
    print(newUser)
    print("Object Saved.")


    let myStringValue = cell.label.text
    request.predicate = NSPredicate (format: "name == %@", myStringValue!)
    do
    {
        let result = try context.fetch(request)
        if result.count > 0
        {
            let nameData = (result[0] as AnyObject).value(forKey: "name") as! String
            print(nameData)

        }
    }
    catch {
        //handle error
        print(error)
    }

    return cell
}

@IBAction func tap(_ sender: Any) {
    let url = "http://jsonplaceholder.typicode.com/users"
    var request = URLRequest(url: URL(string: url)!)
    request.httpMethod = "GET"
    let configuration = URLSessionConfiguration.default
    let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)
    let task = session.dataTask(with: request){(data, response,error)in
        if (error != nil){
            print("Error")
        }
        else{
            do{
                // Array of Data
                let fetchData = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as! NSArray

                for eachData in fetchData {

                    let eachdataitem = eachData as! [String : Any]
                    let name = eachdataitem["name"]as! String
                    let username = eachdataitem["username"]as! String

                    let email = eachdataitem["email"]as! String
                    self.displayDatasssss.append(displyDataClass(name: name, username: username,email : email))
                }
                self.tableView.reloadData()
            }
            catch{
                print("Error 2")
            }

        }
    }
    task.resume()

    }
}



class displyDataClass {
    var name : String
    var username : String
    var email : String

init(name : String,username : String,email :String) {
    self.name = name
    self.username = username
    self.email = email
   }
}

Below code For delete

// delete action two
        let deleteAction = UITableViewRowAction(style: .default, title: "Delete", handler: { (action, indexPath) in
            print("Delete tapped")

            // remove the deleted item from the model
            let appDel:AppDelegate = UIApplication.shared.delegate as! AppDelegate
            let managedObjectContext = appDel.persistentContainer.viewContext
            managedObjectContext.delete(self.displayDatasssssindexPath.row])
            self.milestoneTitles.remove(at: indexPath.row)
            do {
                try managedObjectContext.save()
            } catch _ {
            }

            self.tableView.deleteRows(at: [indexPath], with: .automatic)
           return [editAction, deleteAction]
       }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM