Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSFetchRequest Core Data Swift 3 Backward compatibility

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.

like image 565
Rox Avatar asked Dec 10 '22 14:12

Rox


1 Answers

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)
}
like image 67
Martin R Avatar answered Jan 12 '23 10:01

Martin R