gpt4 book ai didi

ios - Swift - 在基类中使用 'Self' 的类型?

转载 作者:行者123 更新时间:2023-11-30 14:18:18 25 4
gpt4 key购买 nike

我有一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com