我有一个 NSManagedObject 子类 Shop
,我在 swift 中为其定义了以下函数:
// insertions
public class func insertOrUpdateRepresentation(representation: Dictionary<String, AnyObject>, context: NSManagedObjectContext) -> Shop {
let identifier = representation["id"] as! NSNumber
let string = identifier.stringValue
var shop = Shop.fetchObjectWithIdentifier(string, context: context) as! Shop?
// insert if needed
if (shop == nil) {
shop = NSEntityDescription.insertNewObjectForEntityForName(Shop.entityName(), inManagedObjectContext: context) as? Shop
}
// update
shop?.deserializeRepresentation(representation)
return shop!
}
现在,我想为此对象(和其他对象)定义一个基类,我可以在该方法中使用类类型。现在在 Objective C 中,我可以在这里引用“self”来获取当前调用者的类。
// insertions
public class func insertOrUpdateRepresentation(representation: Dictionary<String, AnyObject>, context: NSManagedObjectContext) -> MyManagedObject {
let identifier = representation["id"] as! NSNumber
let string = identifier.stringValue
var obj = (class of the caller).fetchObjectWithIdentifier(string, context: context) as! (class of the caller)?
// insert if needed
if (obj == nil) {
obj = NSEntityDescription.insertNewObjectForEntityForName((class of the caller).entityName(), inManagedObjectContext: context) as? (class of the caller)
}
// update
obj?.deserializeRepresentation(representation)
return obj!
}
如何在 swift 中实现这种功能?
谢谢!
最佳答案
通过使用像这样的 swift Types 来让它工作:
public class func insertOrUpdateRepresentation<T: DDManagedObject>(representation: Dictionary<String, AnyObject>, context: NSManagedObjectContext, type: T.Type) -> T {
let identifier = representation["id"] as! NSNumber
let string = identifier.stringValue
var obj = T.fetchObjectWithIdentifier(string, context: context) as! T?
// insert if needed
if (obj == nil) {
obj = NSEntityDescription.insertNewObjectForEntityForName(T.entityName(), inManagedObjectContext: context) as? T
}
// update
obj?.deserializeRepresentation(representation)
return obj!
}
关于ios - Swift - 在基类中使用 'Self' 的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30851042/