'NSBatchDeleteRequest' 仅适用于 iOS 9.0 或更高版本

'NSBatchDeleteRequest' is only available on iOS 9.0 or newer

我正面临这个问题

'NSBatchDeleteRequest' is only available on iOS 9.0 or newer

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 之前使用的相同功能的代码是什么?

只是一个循环,获取记录并删除它们

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, *) {

在iOS9之前,您必须获取实体的每条记录并将其标记为删除,然后保存更改。

像这样:

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的帮助。