Swift3:将参数传递给NSFetchRequest方法

时间:2016-09-16 07:05:36

标签: swift3 nsfetchrequest

我在项目中使用了一般的CoreData查询方法。

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
}

在Swift 3中,这不起作用。我在Apple的网站上找到了这个:

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

使用Apple示例,我如何将Animal作为参数传递给方法,以使findAnimals更通用?

4 个答案:

答案 0 :(得分:4)

我还没试过这个,但我觉得这样的事情会起作用......

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

你必须使整个函数通用,所以你必须告诉它在调用时它是什么类型。

someObject.findCoreDataObjects<Animal>()

认为应该做的工作。虽然我自己对仿制药不熟悉,但并不完全确定:D

答案 1 :(得分:1)

这个怎么样。

func query<T: NSManagedObject>(table: String, searchPredicate: NSPredicate) -> [T] {
    let context = app.managedObjectContext
    let fetchRequest: NSFetchRequest<T> = NSFetchRequest(entityName: table)
    fetchRequest.predicate = searchPredicate
    let results = try! context.fetch(fetchRequest)
    return results
}

答案 2 :(得分:0)

以下是可能有助于某人的最终结果:

import Foundation
import Cocoa

func addRecord<T: NSManagedObject>(_ type : T.Type) -> T
{
    let entityName = T.description()
    let context = app.managedObjectContext
    let entity = NSEntityDescription.entity(forEntityName: entityName, in: context)
    let record = T(entity: entity!, insertInto: context)
    return record
}

func recordsInTable<T: NSManagedObject>(_ type : T.Type) -> Int
{
    let recs = allRecords(T.self)
    return recs.count
}


func allRecords<T: NSManagedObject>(_ type : T.Type, sort: NSSortDescriptor? = nil) -> [T]
{
    let context = app.managedObjectContext
    let request = T.fetchRequest()
    do
    {
        let results = try context.fetch(request)
        return results as! [T]
    }
    catch
    {
        print("Error with request: \(error)")
        return []
    }
}

func query<T: NSManagedObject>(_ type : T.Type, search: NSPredicate?, sort: NSSortDescriptor? = nil, multiSort: [NSSortDescriptor]? = nil) -> [T]
{
    let context = app.managedObjectContext
    let request = T.fetchRequest()
    if let predicate = search
    {
        request.predicate = predicate
    }
    if let sortDescriptors = multiSort
    {
        request.sortDescriptors = sortDescriptors
    }
    else if let sortDescriptor = sort
    {
        request.sortDescriptors = [sortDescriptor]
    }

    do
    {
        let results = try context.fetch(request)
        return results as! [T]
    }
    catch
    {
        print("Error with request: \(error)")
        return []
    }

}


func deleteRecord(_ object: NSManagedObject)
{
    let context = app.managedObjectContext
    context.delete(object)
}

func deleteRecords<T: NSManagedObject>(_ type : T.Type, search: NSPredicate? = nil)
{
    let context = app.managedObjectContext

    let results = query(T.self, search: search)
    for record in results
    {
        context.delete(record)
    }
}

func saveDatabase()
{
    let context = app.managedObjectContext

    do
    {
        try context.save()
    }
    catch
    {
        print("Error saving database: \(error)")
    }
}

用以下方式调用:

let name = "John Appleseed"

let newContact = addRecord(Contact.self)
newContact.contactNo = 1
newContact.contactName = name

let contacts = query(Contact.self, search: NSPredicate(format: "contactName == %@", name))
for contact in contacts
{
    print ("Contact name = \(contact.contactName), no = \(contact.contactNo)")
}

deleteRecords(Contact.self, search: NSPredicate(format: "contactName == %@", name))

recs = recordsInTable(Contact.self)
print ("Contacts table has \(recs) records")

saveDatabase()

答案 3 :(得分:0)

我在项目中使用这种方式:

static func retrieveRecords<T: NSManagedObject>(table: String, sortDescriptorKey: NSSortDescriptor? = nil) -> [T] {
    do {
        let fetchRequest: NSFetchRequest<T> = NSFetchRequest(entityName: table)
        fetchRequest.sortDescriptors = [sortDescriptorKey!]
        let results = try context.fetch(fetchRequest)
        print("\(results)")
        return results
    } catch let error {
        print("Could not fetch \(error.localizedDescription)")

        return []
    }
}

并称之为:

personen = retrieveRecords(table: "Person", sortDescriptorKey: NSSortDescriptor(key: #keyPath(Person.nachname), ascending: true, selector: #selector(NSString.localizedCompare)))