gpt4 book ai didi

ios - 在 NSBatchDeleteRequest 之后使用核心数据

转载 作者:行者123 更新时间:2023-11-28 15:38:31 25 4
gpt4 key购买 nike

在我的应用程序中,当我从网络服务刷新实体的内容时,我删除了核心数据中的所有记录并插入了所有新记录。但是,很多时候记录并没有从上下文中删除,即使我再次调用上下文也是如此。因此,当我保存时,旧的仍然存在,而我最终只是堆叠在现有的之上,得到很多重复项。我怎样才能完全清除上下文,这样我就不必担心重复?

    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 {}
}

最佳答案

试试下面这个函数:

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
}
}

关于ios - 在 NSBatchDeleteRequest 之后使用核心数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44019202/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com