4

I have converted my code in swift 3. I am using core data in my application. As you know, NSFetchRequest has been changed. In swift 2 it was:

let request = NSFetchRequest(entityName: "UnsyncedTask")

In swift 3:

let request:NSFetchRequest<NSFetchRequestResult> = UnsyncedTask.fetchRequest()

My question is, It only supports ios 10. How can I make it backward ios compatible? I want NSFetchRequest which supports ios 9, ios 10 with swift 3.

Rox
  • 909
  • 11
  • 31

1 Answers1

13

NSFetchRequest(entityName:) is still available in Swift 3. You can use if #available to use the newer API on iOS 10/macOS 10.12 or later, and the older API on older OS versions:

let request: NSFetchRequest<UnsyncedTask>
if #available(iOS 10.0, OSX 10.12, *) {
    request = UnsyncedTask.fetchRequest()
} else {
    request = NSFetchRequest(entityName: "UnsyncedTask")
}
do {
    let results = try context.fetch(request)
    for task in results {
        // ...
    }
} catch let error {
    print(error.localizedDescription)
}
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • Not working for me. My iOS Deployment Target is 9.2 and I have an errors in code above in line `request = Settings.fetchRequest()`. The error is saying: **Cannot assign value of type 'NSFetchRequest' to type 'NSFetchRequest'** `The Settings` is just NSManagedObject generated from model in xCode 7 – Marcin Kapusta Sep 20 '16 at 09:45
  • @MarcinKapusta: But you are using Xcode 8 now? I tested it with a new Xcode 8 project. – Martin R Sep 20 '16 at 09:55
  • @MartinR Yes I'm using xCode 8 now. Do I need to regenerate my models with xCode 8? – Marcin Kapusta Sep 20 '16 at 09:56
  • @MarcinKapusta I strongly think so. Xcode 8 creates a fetchRequest method for each entity. – Martin R Sep 20 '16 at 09:59
  • @MartinR I regenerated my models. It seems that now everything is correct :) What is important You don't need this `if` because on generated model You have this method even in iOS 9 so checking condition if this is iOS 10 is unnecessary I think. – Marcin Kapusta Sep 20 '16 at 10:11
  • 1
    @MartinR Sorry I'm wrong. Now I see the compiler complains about this `Ambiguous use of 'fetchRequest()'` – Marcin Kapusta Sep 20 '16 at 10:14
  • @MarcinKapusta I corrected answer. Now it should work fine. – Nikolay Shubenkov Jul 21 '17 at 09:23