扩展中创建托管对象子类的实例

扩展中创建托管对象子类的实例

本文介绍了如何在 NSManagedObject Swift 扩展中创建托管对象子类的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当为 NSManagedObject 创建一个扩展助手来创建一个新的托管对象子类时,swift 提供了 Self 类型来模仿 instancetype,这很好,但我似乎无法从 AnyObject 进行类型转换.下面的代码没有编译错误 'AnyObject' is not convertible to 'Self'

When creating an extension helper to NSManagedObject to create a new managed object subclass, swift provides the Self type to mimic instancetype which is great, but i can't seem to typecast from AnyObject. The below code does not compile with error 'AnyObject' is not convertible to '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)
    }

}

推荐答案

(现已针对 Swift 3/4 更新.早期 Swift 版本的解决方案可以在编辑历史中找到.)

您可以使用 unsafeDowncast 来转换返回值NSEntityDescription.insertNewObject()Self(这是方法实际调用的类型):

You can use unsafeDowncast to cast the return valueof NSEntityDescription.insertNewObject() to Self(which is the type on which the method is actually called):

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.

works and the compiler infers the type of obj correctly as YourEntity.

这篇关于如何在 NSManagedObject Swift 扩展中创建托管对象子类的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 04:20