摘要核心数据获取请求

时间:2017-12-06 17:31:31

标签: swift core-data

func fetchRequestFromViewContext(nameOfEntity: NSManagedObject) {
    let fetchRequest = NSFetchRequest<nameOfEntity>(entityName: "\(nameOfEntity)")
    do {
        let result = try? CoreDataStack.instance.viewContext.fetch(fetchRequest)

    }
}

尝试抽象核心数据获取请求,从而创建一个类型为托管对象的参数,并将其传递给fetch请求泛型但是没有让我,我是否在正确的轨道上抽象出这个核心数据获取请求?

2 个答案:

答案 0 :(得分:0)

NSFetchRequest(entityName:)需要String,但nameofEntityNSManagedObject。将其更改为String,然后传入实体的类型。您可以使用泛型(下面的<T>)来允许符合NSManagedObject的任何类。

func fetchRequestFromViewContext<T: NSManagedObject>(nameOfEntity: String, type: T.Type) {
    let fetchRequest = NSFetchRequest<T>(entityName: nameOfEntity)
    do {
        let result = try? CoreDataStack.instance.viewContext.fetch(fetchRequest)

    }
}

要打电话给你,你只需要这样做:

fetchRequestFromViewContext(nameOfEntity: "YourEntity", type: YourEntity.self)

答案 1 :(得分:0)

static func fetch<T>(entity: T.Type, withPredicate predicate: NSPredicate? = 
nil) -> Array<T>? where T : NSFetchRequestResult {

let request: NSFetchRequest<T> = NSFetchRequest<T>(entityName: 
String(describing: T.self))
    request.predicate = predicate
    do {
        return try context.fetch(request)
    }catch{
        print(error.localizedDescription)
    }
    return nil
}