swift - 从 CoreData 中删除字符串
问题描述
我在从我的核心数据中删除一个项目时遇到问题,并且查看了许多其他示例和问题 - 他们都说要删除 anNSManagedObject
而我试图删除位于indexPath.row
( 这是 a String
) 的项目。
var itemsArray = [String]()
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
我会在以下函数中添加什么?
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if (editingStyle == .delete) {
}
}
在 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")
}
}
解决方案
为了能够删除您必须使用NSManagedObject
作为数据源的对象
var itemsArray = [Items]()
可以loadItems
减少到
func loadItems() throws {
let request = NSFetchRequest<Items>(entityName: "Items")
request.returnsObjectsAsFaults = false
itemsArray = try context.fetch(request)
}
将do - catch
块放在loadItems()
调用周围并打印error
实例,而不是无意义的文字字符串。
cellForRow
使用中
let item = itemArray[indexPath.row]
let product = item.product
要删除项目,您必须将其从数据源中删除,然后删除上下文中的项目,然后保存上下文:
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
}
}
推荐阅读
- django - Django:模型字段中的用户列表
- r - 更精确地在 r 中导入数据
- r - 从嵌套列表中进行有效抽样
- android - React Native 如何手动将 API 级别更改为 26
- python - 机器人唤醒时向所有用户发送消息
- mysql - 从表中选择一个有限的数字,但全部从连接的表中连接
- java - android旋转屏幕导致文本颜色更改为默认值
- amazon-web-services - 将主机 IP 地址分配给 Docker 容器
- python - 数据抓取 Python - 在 href 中获取标签
- python - 构造 ClassDict 的预期参数为零(对于 pyspark.ml.linalg.SparseVector)