我正面临这个问题
“ NSBatchDeleteRequest”仅在iOS 9.0或更高版本上可用
class func delete(placeId:Int64) {
let context = CoreDataStack.getContext()
let fetch = NSFetchRequest<NSFetchRequestResult>(entityName: "Place")
fetch.predicate = NSPredicate(format: "id = \(placeId)")
let request = NSBatchDeleteRequest(fetchRequest: fetch)
do {
_ = try context.execute(request)
} catch {
fatalError("Failed to execute request: \(error)")
}
CoreDataStack.saveContext()
}
iOS 9之前用于相同功能的代码是什么?
答案 0 :(得分:1)
只是一个循环,获取记录并将其删除
let context = CoreDataStack.getContext()
let fetch = NSFetchRequest<NSFetchRequestResult>(entityName: "Place")
fetch.predicate = NSPredicate(format: "id = \(placeId)")
let fetchResults = try context.fetch(request)
for anItem in fetchResults {
context.delete(anItem)
}
您可以添加此if
子句以同时考虑两种方式
if #available(iOS 9, macOS 10.11, *) {
答案 1 :(得分:0)
在iOS 9之前,您必须获取实体的每条记录并将其标记为删除,然后保存更改。
类似这样的东西:
context.performBlockAndWait
{
if let result = try? context.fetch(fetch)
{
for object in result
{
context.delete(object)
}
}
do
{
// After mark to delete you must save the context
try context.save()
}
catch
{
// Error
}
}
感谢user1046037的帮助。