【发布时间】:2018-10-09 11:09:17
【问题描述】:
我有一个核心数据类 List 继承自抽象类型 Synchronizable。后者是我打算与我的服务器同步的其他几个类的父类。
我想在Synchronizable 中加入一个类函数,它返回服务器上具有特定 ID 的对象:
class func withIDOnServer(_ pk:String, inMOC context:NSManagedObjectContext -> Self?
并将其用作
List.withIDOnServer(pk:"1234", context)
我遇到的问题是我无法将结果转换为子类类型。这是我的代码:
extension Synchronizable {
// return the object with ID xxx on server.
class func withIDOnServer(_ pk:String, inMOC context:NSManagedObjectContext) throws -> Self? {
let entityName = String(describing: self)
let request = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
request.predicate = NSPredicate(format:"'pk' = %@", pk)
do {
let results = try context.fetch(request) as! [Self]
guard results.count == 1 else {
if results.count > 1 {
throw fetchError.moreThanOne(pk: pk)
}
else { // results.count == 0
return nil
}
}
return results.first as! Self?
}
catch let error {
throw fetchError.cannotFetch(error.localizedDescription)
}
}
}
问题是在函数体中使用了Self。 (我也试过Self?和type(of:self),没有运气)
如何返回与子类相同类型的对象?是使用协议的唯一方法(函数体中允许Self)吗?
【问题讨论】:
标签: swift inheritance core-data return-type introspection