我尝试从coredata中删除一行。我处理这行但我没有删除。当我尝试 context.delete()它需要()中的 NSManagedObject 。我如何将此结果转换为NSManagedObject?
func deleteElement(postUid:String){
let appDel:AppDelegate = (UIApplication.shared.delegate as! AppDelegate)
let context:NSManagedObjectContext = appDel.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Posts")
let predicate = NSPredicate(format: "postUid == %@", postUid as CVarArg)
fetchRequest.predicate = predicate
do {
let result = try context.fetch(fetchRequest)
print("Result \(result)")
try context.save()
} catch {
print("Error \(error)")
}
}
//结果打印
Result [<Posts: 0x6080002901d0> (entity: Posts; id: 0xd000000000640000 <x-coredata://9A330E28/Posts/p25> ; data: {
item = "<relationship fault: 0x60c00022b900 'item'>";
lastMessageTime = "2018-05-23";
parentUid = nil;
postUid = "15e43d16";
title = Title;
userUid = ".."; })]
答案 0 :(得分:2)
let result = try context.fetch(request)
for object in result {
let obj = object as! NSManagedObject
context.delete(obj)
}
try context.save()
您基本上需要获取对象,然后逐个删除它们。然后你就像往常一样保存上下文。