如何在NSManagedObject Swift扩展中创建托管对象子类的实例?

如何在NSManagedObject Swift扩展中创建托管对象子类的实例?,第1张

如何在NSManagedObject Swift扩展中创建托管对象子类的实例?

(现在为Swift 3/4更新。可以在编辑历史记录中找到早期Swift版本的解决方案。)

您可以使用

unsafeDowncast
到的返回值转换
NSEntityDescription.insertNewObject()
Self

(这是该方法实际上是所谓的类型):

extension NSManagedObject {    class func create(in context: NSManagedObjectContext) -> Self {        let classname = entityName()        let object = NSEntityDescription.insertNewObject(forEntityName: classname, into: context)        return unsafeDowncast(object, to: self)    }    // Returns the unqualified class name, i.e. the last component.    // Can be overridden in a subclass.    class func entityName() -> String {        return String(describing: self)    }}

然后

let obj = YourEntity.createInContext(context)

工作,并且编译器

obj
正确的类型推断为
YourEntity



欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5476653.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-12
下一篇2022-12-12

发表评论

登录后才能评论

评论列表(0条)

    保存