Can someone explain class func fetchRequest() ?

Hi


I am getting into the new core data API released for ios 10. I like the generics, but there one part of it that suprises me. Firstly, when I tried this:

        let fr = Currency.fetchRequest()

where Currency is a core-data entity class I got a red circle telling me "Abiguous use of fetchRequest()".
If I jump to definition it goes to a class func fetchRequest of another class. ??


If I change it to:

let fr: NSFetchRequest<Currency> = Currency.fetchRequest()

it compiles. Jump to definition takes me to the automatically generated method in Currency+CoreDataProperties.swift:

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Currency> {
        return NSFetchRequest<Currency>(entityName: "Currency");
    }


But what makes it suprising is that there is a function in the base class NSManagedObject:

    /* A new fetch request initialized with the Entity represented by this subclass.
      This property's getter is only legal to call on subclasses of NSManagedObject that represent
      a single entity in the model.
     */
    @available(iOS 10.0, *)
    open class func fetchRequest() -> NSFetchRequest<NSFetchRequestResult>


THis is confusing. If each class needs its own fetchRequest method as in Currency+CoreDataProperties.swift to provide the entity name, what can the one on NSManagedObject do? If it is not needed, why can't we have a single generic function that can be called on the subclasses?


---

Mark

Replies

With these definitions, your code was ambiguous between Currency.fetchRequest and NSManagedObject.fetchRequest.


The hidden twist is that Currency.fetchRequest is declared "@nonobjc". That means its name is really something mangled — something other than "fetchRequest" — so they are two different, unrelated functions. It just happens that their names look the same in source code, hence the ambiguity.


My guess is that the Currency function is a strongly-typed Swift wrapper that calls the original Obj-C method in NSManagedObject.


Without any additional information, it seems like it was a poor choice for the Currency+CoreDataProperties definition to have the same source-code name as the underlying class method. It might be worth a bug report.