[英]Deleting String from CoreData
I'm having problems deleting an item from my Core Data, and having looked at lots of other examples and questions - they all say about deleting an NSManagedObject
whereas I'm trying to delete the item at the indexPath.row
(which is a String
). 我在从核心数据中删除项目时遇到了问题,并且查看了许多其他示例和问题-他们都说过要删除NSManagedObject
而我正在尝试在indexPath.row
(它是String
上删除项目)。
var itemsArray = [String]()
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
What would I put in the following function? 我将在以下功能中添加什么?
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if (editingStyle == .delete) {
}
}
Loading items in Core Data 在核心数据中加载项目
func loadItems() {
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Items")
request.returnsObjectsAsFaults = false
do {
let results = try context.fetch(request)
if results.count > 0 {
for result in results as! [NSManagedObject] {
if let product = result.value(forKey: "product") as? String {
self.itemsArray.append(product)
}
}
}
} catch {
print("Error")
}
}
To be able to delete the object you have to use the NSManagedObject
as data source 为了能够删除对象,您必须使用NSManagedObject
作为数据源
var itemsArray = [Items]()
The loadItems
can be reduced to loadItems
可以减少为
func loadItems() throws {
let request = NSFetchRequest<Items>(entityName: "Items")
request.returnsObjectsAsFaults = false
itemsArray = try context.fetch(request)
}
Put the do - catch
block around the loadItems()
call and print the error
instance, not a meaningless literal string. 将do - catch
块放在loadItems()
调用周围,并打印error
实例,而不是无意义的文字字符串。
In cellForRow
use 在cellForRow
使用
let item = itemArray[indexPath.row]
let product = item.product
To delete the item you have to remove it from the data source, then delete the item in the context and then save the context: 要删除该项目,您必须将其从数据源中删除,然后在上下文中删除该项目,然后保存上下文:
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let objectToDelete = itemArray[indexPath.row]
itemArray.remove(at: indexPath.row)
context.delete(objectToDelete)
// here add code to save the context
self.tableView.deleteRows(at: [indexPath], with: .fade) // and you have to update the table view
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.