In NSManagedObject
there is a method:
class func fetchRequest() -> NSFetchRequest<NSFetchRequestResult>
If you use automatic code generation for model objects, then each generated class will have a method:
@nonobjc public class func fetchRequest() -> NSFetchRequest<ClassName> {
return NSFetchRequest<ClassName>(entityName: "EntityName")
}
For example if you have the following hierarchy of models:
Animal
- Cat
- Dog
Then XCode will generate the following methods:
// for Animal model object
@nonobjc public class func fetchRequest() -> NSFetchRequest<Animal> {
return NSFetchRequest<Animal>(entityName: "Animal")
}
// for Cat model object
@nonobjc public class func fetchRequest() -> NSFetchRequest<Cat> {
return NSFetchRequest<Cat>(entityName: "Cat")
}
// for Dog model object
@nonobjc public class func fetchRequest() -> NSFetchRequest<Dog> {
return NSFetchRequest<Dog>(entityName: "Dog")
}
In this case, when you write Cat.fetchRequest()
the compiler does not know which of the 3 overloads to choose.
- This request will return all animals, cats, and dogs:
let request: NSFetchRequest<Animal> = Cat.fetchRequest()
- This request will return only cats:
let request: NSFetchRequest<Cat> = Cat.fetchRequest()
- And this query will return all the animals, cats and dogs, but the result will not be typed:
let request: NSFetchRequest<NSFetchRequestResult> = Cat.fetchRequest()