仅适用于iOS 10的Swift 3中的NSBatchDeleteRequest?

时间:2016-10-07 19:42:36

标签: ios swift xcode

因此,将我的代码迁移到Swift 3让我有点卡住了。现在似乎NSBatchDeleteRequest需要iOS 10?我可以进行代码构建的唯一方法是使用以下代码段:

func removeAllChargerData(){
    // Remove all charging data from persistent storage
    let fetchRequest: NSFetchRequest<NSFetchRequestResult> = ChargerPrimary.fetchRequest()
    let entity = NSEntityDescription.entity(forEntityName: "ChargerPrimary", in: self.secondMoc)
    fetchRequest.entity = entity
    let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)

    do {
        try self.secondMoc.execute(deleteRequest)
    } catch {
        let deleteError = error as NSError
        NSLog("\(deleteError), \(deleteError.localizedDescription)")
    }

}

但是,会出现一条警告,表示fetchRequest()仅在iOS 10及更新版本中可用。如果我按以下方式定义fetchRequest,则会收到错误,因为它期望fetchRequest具有NSFetchRequestResult参数类型:

let fetchRequest = NSFetchRequest<ChargerPrimary>(entityName: "ChargerPrimary")

2 个答案:

答案 0 :(得分:9)

您只需要为通用指定正确的类型:

let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "ChargerPrimary")

答案 1 :(得分:2)

可能它在IOS 10中也适合我

 let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "ChargerPrimary")
 let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)

你应该像这样使用fetchrequest而不给varible

特定的类型

对于IOS 9,这是DEMO