Need generic FetchedResultsController builder (Swift)

298 views Asked by At

I created a method to build an frc:

private func buildFRC<T:NSManagedObject>(entity: T, sortKey: String) 
    -> NSFetchedResultsController<T>? {

    let fetchRequest: NSFetchRequest = T.fetchRequest()
    let sortDescriptor1 = NSSortDescriptor(key: sortKey, ascending: true)
    fetchRequest.sortDescriptors = [sortDescriptor1]

    searchContext.reset()

    var frc: NSFetchedResultsController<T>? =
        NSFetchedResultsController<T>(
        fetchRequest:            fetchRequest as! NSFetchRequest<T>,
        managedObjectContext:   searchContext,
        sectionNameKeyPath:     nil,   
        cacheName:              nil)   
    frc!.delegate = self                

    try? frc!.performFetch()
    return frc
}

I want to call something like this from within a closure:

self.frc = self.buildFRC(entity: ObjectName, sortKey: "trackName")

but I'm getting this error:

"Cannot convert value of type 'ObjectName.Type' to expected argument type 'NSManagedObject'".

Yet, ObjectName is the class name of an NSManagedObject. I tried myself but eventually I just keep chasing errors in a circle.

1

There are 1 answers

3
Tom Harrington On BEST ANSWER

Your function declaration doesn't mean quite what you think it does.

private func buildFRC<T:NSManagedObject>(entity: T, sortKey: String) -> NSFetchedResultsController<T>? 

This means that T must be a subclass of NSManagedObject, and that the first argument must be an instance of T. When you call it like this

self.frc = self.buildFRC(entity: ObjectName, sortKey: "trackName")

...you're passing in the subclass as the first argument, when your declaration expects an instance.

It's not hard to fix, because you don't need to include T as an argument. In general, Swift generics don't need you to pass the type as an argument-- the type comes from how the function is used. Drop that argument and rewrite the declaration as

private func buildFRC<T:NSManagedObject>(sortKey: String) -> NSFetchedResultsController<T>? {

Then call the function with something like

self.frc: NSFetchedResultsController<ObjectName>? = self.buildFRC(sortKey: "trackName")

Swift will figure out that T represents ObjectName in that call and the code will work.

On a tangential note, your call to searchContext.reset() is kind of dangerous and probably not needed. If you fetch some objects from the context and then call this function later on, the reset will cause all of those previously fetched objects to become invalid. Using them would crash your app.