Xcode 8 在您的 NSManagedObject
子类上提供了一个自动生成的 extension
,看起来像这样:
// Animal+CoreDataProperties.swift
import Foundation
import CoreData
extension Animal {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Animal> {
return NSFetchRequest<Animal>(entityName: "Animal");
}
// etc...
}
这很棒,因为我们不再需要硬编码字符串来创建 NSFetchRequest
对象。但是,Apple 尚未提供引用此方法的协议(protocol),也未提供引用 entityName
本身的协议(protocol)。
例如,如果我想创建这样的方法:
protocol ManagedObjectType: class {}
extension ManagedObjectType where Self: NSManagedObject {
static func findOrCreate(inContext context: NSManagedObjectContext, matchingPredicate predicate: NSPredicate) -> Self {
// etc...
}
}
...我无法利用任何 NSManagedObject
子类的 fetchRequest
方法(因为它只定义在子类),所以我不得不自己再次对这些字符串进行硬编码(即使 Xcode 已经这样做了)。
知道解决这个问题的方法吗?我在想这些事情:
protocol ManagedObjectType: class {
static func fetchRequest() -> NSFetchRequest<NSFetchRequestResult>
}
extension Animal: ManagedObjectType {}
但这不起作用,因为协议(protocol)不支持 where
子句,所以我不能指定 Self
是一个 NSFetchRequestResult
,这意味着当我开始使用它时,像这样:
let request: NSFetchRequest<Self> = self.fetchRequest()
... Xcode 给我这个错误:
'fetchRequest' produces 'NSFetchRequest<NSFetchRequestResult>', not the expected contextual result type 'NSFetchRequest<Self>'
有人解决过这个问题吗?
最佳答案
您可以为此目的使用模板。所以你的代码看起来像这样:
static func findOrCreate<T: NSManagedObject>(inContext context: NSManagedObjectContext, matchingPredicate predicate: NSPredicate) -> T {
// etc...
}
关于ios - findOrCreate 在 Swift 3 中没有硬编码 entityName,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40630912/