Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply the type to a NSFetchRequest instance?

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 
like image 234
Deniss Avatar asked Jun 14 '16 11:06

Deniss


People also ask

How do you start your NSFetchRequest?

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.

How do I get NSManagedObject?

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.

What class would you use to filter fetched results from Core Data?

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.

What are fetched properties in Core Data?

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.


1 Answers

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.

like image 167
Sulthan Avatar answered Sep 19 '22 17:09

Sulthan