简体   繁体   English

删除CoreData对象

[英]Delete CoreData object

I am still struggling with CoreData to start the week haha. 我仍在努力与CoreData一起开始一周哈哈。 I finally succeeded in saving and fetching my array, now is time to edit and delete. 我终于成功地保存和获取了我的阵列,现在该进行编辑和删除了。

I'm adding the delete function first but I'm having trouble passing in the correct argument: 我先添加了delete函数,但是在传递正确的参数时遇到了麻烦:

Core Data functions: 核心数据功能:

class CDHandler: NSObject {

private class func getContext() -> NSManagedObjectContext {
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    return appDelegate.persistentContainer.viewContext
}

class func saveObject(name:String, code:String, symbol:String, placeholder:String, amount:String) -> Bool {
    let context = getContext()
    let entity = NSEntityDescription.entity(forEntityName: "CryptosMO", in: context)
    let managedObject = NSManagedObject(entity: entity!, insertInto: context)

    managedObject.setValue(name, forKey: "name")
    managedObject.setValue(code, forKey: "code")
    managedObject.setValue(symbol, forKey: "symbol")
    managedObject.setValue(placeholder, forKey: "placeholder")
    managedObject.setValue(amount, forKey: "amount")

    do {
        try context.save()
        return true
    } catch {
        return false
    }
}

class func fetchObject() -> [CryptosMO]? {
    let context = getContext()
    var cryptos: [CryptosMO]? = nil

    do {
        cryptos = try context.fetch(CryptosMO.fetchRequest()) as? [CryptosMO]
        return cryptos
    } catch {
        return cryptos
    }
}

class func deleteObject(crypto: CryptosMO) -> Bool {
    let context = getContext()
    context.delete(crypto)

    do {
        try context.save()
        return true
    } catch {
        return false
    }
}

} }

Creating and saving the array : 创建并保存数组:

    if addedCrypto != "" {
        if addedCrypto == "Bitcoin BTC" {
            if CDHandler.saveObject(name: "Bitcoin", code: "bitcoin", symbol: "BTC", placeholder: "BTC Amount", amount: "0.0") {
                for crypto in CDHandler.fetchObject()! {
                    print("\(String(describing: crypto.name))'s symbol is \(String(describing: crypto.symbol))")
                }
            }
        }
    }

Fetching Core Data for the TableView: 获取TableView的核心数据:

override func viewWillAppear(_ animated: Bool) {
    tableView.delegate = self
    tableView.dataSource = self


    if CDHandler.fetchObject() != nil {
        cryptos = CDHandler.fetchObject()!
        tableView.reloadData()
    }
}

TableView functions: TableView函数:

extension WalletTableViewController: UITableViewDelegate, UITableViewDataSource, CryptoCellDelegate {


func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return cryptos.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! WalletTableViewCell

    cell.cryptoNameLabel.text = cryptos[indexPath.row].name
    cell.amountTextField.placeholder = cryptos[indexPath.row].placeholder

    cell.delegate = self
    cell.amountTextField.delegate = self

    return cell
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
        cryptos.remove(at: indexPath.row)
        tableView.deleteRows(at: [indexPath], with: .fade)
        CDHandler.deleteObject(crypto: cryptos) // <----- Cannot convert value of type '[CryptosMO]' to expected argument type 'CryptosMO'
    }
}

} }

What is the problem here? 这里有什么问题? I can change func deleteObject(crypto: CryptosMO) to func deleteObject(crypto: [CryptosMO]) but then I get Cannot convert value of type '[CryptosMO]' to expected argument type 'NSManagedObject' . 我可以将func deleteObject(crypto: CryptosMO)更改为func deleteObject(crypto: [CryptosMO])但随后我Cannot convert value of type '[CryptosMO]' to expected argument type 'NSManagedObject'

I read that delete() only take an NSManagedObject as its sole argument so I believe I created an incorrect object in the first place to be able to delete it?? 我读到delete()仅将NSManagedObject作为其唯一参数,因此我相信我首先创建了一个不正确的对象就可以将其删除?

Just call this method and pass entity with managedObject which you want to delete: 只需调用此方法,然后将实体与要删除的managedObject一起传递即可:

func deleteData(entity:String,deleteObject:NSManagedObject){
    //for iOS 10+
           // let delegate = UIApplication.shared.delegate as? AppDelegate
           // let context = delegate!.persistentContainer.viewContext
            let context = getContext()
            context.delete(deleteObject)
            do {
                try context.save()
            } catch let error as NSError {
                print("Could not save. \(error), \(error.userInfo)")
            }

        }


 func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
        let selectedManagedObject = cryptos[indexPath.row]
        deleteData(entity:"yourEntityName",deleteObject: selectedManagedObject)
            cryptos.remove(at: indexPath.row)
            tableView.deleteRows(at: [indexPath], with: .fade)
        }
    }

same like save method you can edit, just you need to pass the managedObject which you want to edit: 就像可以编辑的save方法一样,只是需要传递要编辑的managedObject

class func updateObject(name:String, code:String, symbol:String, placeholder:String, amount:String,selectedManagedObject:NSManagedObject) {
    let context = getContext()

    selectedManagedObject.setValue(name, forKey: "name")
    selectedManagedObject.setValue(code, forKey: "code")
    selectedManagedObject.setValue(symbol, forKey: "symbol")
    selectedManagedObject.setValue(placeholder, forKey: "placeholder")
    selectedManagedObject.setValue(amount, forKey: "amount")

    do {
        try context.save()
    } catch let error as NSError {
        print("Could not save. \(error), \(error.userInfo)")
    }

}

When you call CDHandler.deleteObject(crypto: ...) just pass (crypto: cryptos[indexPath.row]) instead of (crypto: cryptos) . 当您调用CDHandler.deleteObject(crypto: ...)只需传递(crypto: cryptos[indexPath.row])而不是(crypto: cryptos)

    ...
    CDHandler.deleteObject(crypto: cryptos[indexPath.row])
    cryptos.remove(at: indexPath.row)
    tableView.deleteRows(at: [indexPath], with: .fade)

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

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