删除CoreData对象
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了删除CoreData对象相关的知识,希望对你有一定的参考价值。
哈哈,我仍在努力与CoreData
开始一周。我终于成功保存并获取了我的数组,现在是时候编辑和删除了。
我首先添加了删除函数,但是我无法传递正确的参数:
核心数据功能:
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
}
}
}
创建和保存数组:
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))")
}
}
}
}
获取TableView的核心数据:
override func viewWillAppear(_ animated: Bool) {
tableView.delegate = self
tableView.dataSource = self
if CDHandler.fetchObject() != nil {
cryptos = CDHandler.fetchObject()!
tableView.reloadData()
}
}
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'
}
}
}
这里有什么问题?我可以将func deleteObject(crypto: CryptosMO)
改为func deleteObject(crypto: [CryptosMO])
然后我得到Cannot convert value of type '[CryptosMO]' to expected argument type 'NSManagedObject'
。
我读到delete()
只把NSManagedObject
作为唯一的参数,所以我相信我首先创建了一个不正确的对象,以便能够删除它?
答案
只需调用此方法并使用要删除的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)
}
}
与您可以编辑的保存方法相同,只需要传递要编辑的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)")
}
}
另一答案
当你打电话给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)
以上是关于删除CoreData对象的主要内容,如果未能解决你的问题,请参考以下文章