在我的应用程序中,当我从Web服务刷新实体的内容时,我删除了我的Core Data中的所有记录并插入了所有新记录。但是,很多时候记录不会从上下文中删除,即使我再次调用上下文。因此,当我保存时,旧的保留,并且我最终堆叠在现有的堆叠之上,获得大量重复。我怎样才能完全清除上下文,所以我不需要担心重复?
var appDelegate = UIApplication.shared.delegate as! AppDelegate
var context = appDelegate.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "V_ServiceDetails")
// Clear all
let request = NSBatchDeleteRequest(fetchRequest: fetchRequest)
do {
let result = try context.execute(request)
} catch {}
appDelegate = UIApplication.shared.delegate as! AppDelegate
context = appDelegate.persistentContainer.viewContext
// Add new ones
for svc in self.svcs {
let result = NSEntityDescription.insertNewObject(forEntityName: "V_ServiceDetails", into: context)
result.setValue(svc.Car_VIN, forKey: "car_VIN")
result.setValue(svc.Cust_Veh_ID, forKey: "cust_Veh_ID")
do { try context.save() } catch {}
}
答案 0 :(得分:1)
从Apple docs on batch delete开始,它表示删除是直接在SQL级别完成的。您在内存中的对象中删除 NOT REFLECTED ,因此您需要在删除后更新应用。请参阅链接页面上的执行后更新应用程序部分。
答案 1 :(得分:0)
尝试以下功能:
func deleteAll() {
// Managed Object Context
let managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
// Save the changes of the Managed Object Context before executing the Batch Delete Request
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Error
}
}
// Craete a Fetch Request
let fetchRequest: NSFetchRequest<ManagedObject> = ManagedObject.fetchRequest()
// Initiliaze the Batch Delete Request
let batchDeleteRequest = NSBatchDeleteRequest.init(fetchRequest: fetchRequest as! NSFetchRequest<NSFetchRequestResult>)
// Configure the Batch Delete Request
batchDeleteRequest.resultType = .resultTypeCount
do {
// Execute the Batch Delete Request
try managedObjectContext.execute(batchDeleteRequest)
// Reset the Managed Object Context
managedObjectContext.reset()
// try self.fetchedResultsController.performFetch()
// If you have a Table View? Use this function
// self.tableView.reloadData()
} catch {
// Error
}
}
答案 2 :(得分:0)
这对我有用。
var e = 1
while e <= self.items!.count {
self.context.delete(self.items![e - 1])
// Save the data
do {
try self.context.save()
}
catch {
}
e = e + 1
}