一尘不染

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

swift

当创建扩展助手来NSManagedObject创建新的托管对象子类时,swift提供了Self一种可以模仿的类型,instancetype这很好,但是我似乎无法从中进行类型转换AnyObject。以下代码无法编译,错误为
“ AnyObject”无法转换为“ Self”

救命?

extension NSManagedObject
{
    class func createInContext(context:NSManagedObjectContext) -> Self {
        var classname = className()
        var object: AnyObject = NSEntityDescription.insertNewObjectForEntityForName(classname, inManagedObjectContext: context)
        return object
    }


    class func className() -> String {
        let classString = NSStringFromClass(self)
        //Remove Swift module name
        let range = classString.rangeOfString(".", options: NSStringCompareOptions.CaseInsensitiveSearch, range: Range<String.Index>(start:classString.startIndex, end: classString.endIndex), locale: nil)
        return classString.substringFromIndex(range!.endIndex)
    }

}

阅读 264

收藏
2020-07-07

共1个答案

一尘不染

(现在为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

2020-07-07