简体   繁体   English

如何使用Swift删除coredata中的特定记录?

[英]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.在我的场景中,我将 JSON 数据加载到 CoreData 中,之后我将获取到 Tableview。 Now, Each and every tableview cell have swipe with Delete and Edit button.现在,每个 tableview 单元格都可以使用“ Delete和“ Edit按钮进行滑动。 If I click delete I need to remove data from coredata and tableview both place.如果我单击删除,我需要从 coredata 和 tableview 两个地方删除数据。

My JSON Structure我的 JSON 结构

   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 JSON 加载到 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.仅使用提供的User类。

First of all declare a data source array (replacing displayDatasssss )首先声明一个数据源数组(替换displayDatasssss

var users = [User]()

In the tap method load the data and insert new items in the Core Data stack.tap方法中加载数据并在 Core Data 堆栈中插入新项目。 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 .由于User只有nameid属性,因此将email分配给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 viewviewDidLoadCoreData获取数据并重新加载表视图

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 elsecellForRow中将属性值分配给标签,没有别的

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注意:总是打印错误,不要忽略它们或只打印无意义的文字字符串

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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