eggrice eggrice - 2 months ago 47
iOS Question

Cannot invoke 'fetch' with an argument list of type '(NSFetchRequest<NSFetchRequestResult>)'

I have created a helper function to load

NSManagedObject
s using Swift 3, which supports iOS 9.0+.

class func loadContext(entityName: String, fetchConfiguration: ((NSFetchRequest<NSManagedObject>) -> Void)?) -> AnyObject? {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
// Fetch requested data
let dataFetchRequest = NSFetchRequest<NSManagedObject>(entityName: entityName)

// Configure the fetch request with user parameters
if fetchConfiguration != nil {
fetchConfiguration!(dataFetchRequest)
}

do {
return try appDelegate.managedObjectContext.fetch(dataFetchRequest as! NSFetchRequest<NSFetchRequestResult>)
} catch {
print("Failed to fetch feed data, critical error: \(error)")
}

return nil
}


However I get the following error:

Cannot invoke 'fetch' with an argument list of type '(NSFetchRequest<NSFetchRequestResult>)'


I have also tried several variants, such as having
let dataFetchRequest = NSFetchRequest<NSFechRequestResult>(entityName: entityName)
and they all run into the same error.

Answer

The changes were a lot simpler, it seems as though xcode wrongfully inferences the "AnyObject" type when converting code from swift-2 to 3.0.

For reference this is the fixed function from @dmorrow's solution.

class func loadContext(entityName: String, fetchConfiguration: ((NSFetchRequest<NSManagedObject>) -> Void)?) -> [NSManagedObject]? {
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    // Fetch requested data
    let dataFetchRequest = NSFetchRequest<NSManagedObject>(entityName: entityName)

    // Configure the fetch request with user parameters
    fetchConfiguration?(dataFetchRequest)

    do {
        return try appDelegate.managedObjectContext.fetch(dataFetchRequest)
    } catch {
        print("Failed to fetch feed data, critical error: \(error)")
    }

    return nil
}