In Swift 2 the following code was working:
let request = NSFetchRequest(entityName: String)
but in Swift 3 it gives error:
Generic parameter "ResultType" could not be inferred
because NSFetchRequest
is now a generic type. In their documents they wrote this:
let request: NSFetchRequest<Animal> = Animal.fetchRequest
so if my result class is for example Level
how should I request correctly?
Because this not working:
let request: NSFetchRequest<Level> = Level.fetchRequest
You initialize an instance of NSFetchRequest as generic type: NSFetchRequest<Venue> . At a minimum, you must specify a NSEntityDescription for the fetch request. In this case, the entity is Venue . You initialize an instance of NSEntityDescription and use it to set the fetch request's entity property.
Still inside the Core Data editor, go to the Editor menu and choose Create NSManagedObject Subclass. Make sure your data model is selected then click Next. Make sure the Commit entity is checked then click Next again.
Core Data fetch requests can use predicates in SwiftUI just like they can with UIKit, all by providing a predicate property to your @FetchRequest property wrapper. If you followed my Core Data and SwiftUI set up instructions, you've already injected your managed object context into the SwiftUI environment.
Fetched Properties in Core Data are properties that return an array value from a predicate. A fetched property predicate is a Core Data query that evaluates to an array of results.
let request: NSFetchRequest<NSFetchRequestResult> = Level.fetchRequest()
or
let request: NSFetchRequest<Level> = Level.fetchRequest()
depending which version you want.
You have to specify the generic type because otherwise the method call is ambiguous.
The first version is defined for NSManagedObject
, the second version is generated automatically for every object using an extension, e.g:
extension Level { @nonobjc class func fetchRequest() -> NSFetchRequest<Level> { return NSFetchRequest<Level>(entityName: "Level"); } @NSManaged var timeStamp: NSDate? }
The whole point is to remove the usage of String constants.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With