Search code examples
swift3nsfetchrequest

Swift3: Passing parameters into NSFetchRequest method


I use a general CoreData query method in my project.

func query(table: String, searchPredicate: NSPredicate) -> [AnyObject]
{
    let context = app.managedObjectContext

    let fetchRequest = NSFetchRequest(entityName: table)

    fetchRequest.predicate = searchPredicate

    let results = try! context.fetch(fetchRequest)
    return results
}

In Swift 3 this doesn't work. I found this on Apple's web site:

func findAnimals() 
{
    let request: NSFetchRequest<Animal> = Animal.fetchRequest
    do 
    {
        let searchResults = try context.fetch(request)
        ... use(searchResults) ...
    } 
    catch 
    {
        print("Error with request: \(error)")
    }
}

Using the Apple example, how would I pass Animal in to the method as a parameter to make findAnimals more generic?


Solution

  • I haven't tried this but I think something like this would work...

    func findCoreDataObjects<T: NSManagedObject>() -> [T] {
        let request = T.fetchRequest
        do 
        {
            let searchResults = try context.fetch(request)
            ... use(searchResults) ...
        } 
        catch 
        {
            print("Error with request: \(error)")
        }
    }
    

    You have to make the entire function generic and so you have to tell it what type T is when calling it.

    someObject.findCoreDataObjects<Animal>()
    

    I think that should do the job. Not entirely certain though as I'm new to generics myself :D