我正在尝试从coreData中删除整个记录。我已经检索了数据并将其放在一个数组中进行操作(我有另一个函数让用户使用这种方法编辑数据并且它工作正常)但我无法弄清楚如何删除记录。 [.remove(at:index)]不起作用,下面的代码也不起作用。我可以将所有字段设置为空,但这不是我想要的,我希望记录完全消失。 我找到了类似问题的解决方案,但无济于事
@IBAction func Delete(_ sender: UIButton) { // The delete function
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "DestinationsOne")
let context = appDelagate.persistentContainer.viewContext
var destArray = [DestinationsOne]() // The data array
do {
try destArray = context.fetch(request) as! [DestinationsOne]} //Fetching the data and placing it in the array
catch{
//error message
}
for index in (0..<destArray.count - 1){ //Go through the records
if destArray[index].destID == IDTitle!{ //Picks the record to edit
let object = destArray[index]
context.delete(object
}
appDelagate.saveContext()
}
答案 0 :(得分:1)
我想出了这个。我发布解决方案以防其他人有同样的问题
JavaScript
答案 1 :(得分:1)
Why not applying a predicate to search this particular record. It's much more efficient than looping through a huge list.
func deleteRecords() { //The function to delete the record
let moc = getContext()
let fetchRequest = NSFetchRequest<DestinationsOne>(entityName: "DestinationsOne")
let predicate = NSPredicate(format: "destID == %@", self.IDTitle)
fetchRequest.predicate = predicate
do {
let resultdata = try moc.fetch(fetchRequest) // no type cast needed
if let objectToDelete = resultdata.first {
moc.delete(objectToDelete) // delete the object
try moc.save() // Save the delete action
}
} catch {
print("Could not save error: ", error)
}
}
答案 2 :(得分:0)
以下是您的代码的一些问题:
performBackgroundTask
对核心数据进行所有更改appDelagate.saveContext
。 Apple的模板代码错误。你永远不应该写入viewContext,所以你永远不应该有理由保存它。IDTitle
在哪里设置?你确定它不是零吗?for index in (0..<destArray.count - 1){
可以替换为更清晰的for (index, element) in destArray.enumerated() {
。