How can I create instances of managed object subclasses in a NSManagedObject Swift extension?

两盒软妹~` 提交于 2019-12-16 22:47:29

问题


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'

Help?

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)
    }

}

回答1:


(Updated for Swift 3/4 now. Solutions for earlier Swift versions can be found in the edit history.)

You can use unsafeDowncast to cast the return value of 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)
    }
}

Then

let obj = YourEntity.createInContext(context)

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




回答2:


Here is a different approach to solve the problem, by implementing an initializer method (tested with Xcode 7.1):

extension NSManagedObject {

    // Returns the unqualified class name, i.e. the last component.
    // Can be overridden in a subclass.
    class func entityName() -> String {
        return String(self)
    }

    convenience init(context: NSManagedObjectContext) {
        let eName = self.dynamicType.entityName()
        let entity = NSEntityDescription.entityForName(eName, inManagedObjectContext: context)!
        self.init(entity: entity, insertIntoManagedObjectContext: context)
    }
}

Init methods have an implicit return type of Self and no casting tricks are necessary.

let obj = YourEntity(context: context)

creates an object of the YourEntity type.


Swift 3/4 update:

extension NSManagedObject {

    // Returns the unqualified class name, i.e. the last component.
    // Can be overridden in a subclass.
    class func entityName() -> String {
        return String(describing: self)
    }

    convenience init(context: NSManagedObjectContext) {
        let eName = type(of: self).entityName()
        let entity = NSEntityDescription.entity(forEntityName: eName, in: context)!
        self.init(entity: entity, insertInto: context)
    }
}



回答3:


In Swift 2 there is a very smart solution using a protocol and a protocol extension

protocol Fetchable
{
  typealias FetchableType: NSManagedObject

  static var entityName : String { get }
  static func createInContext(context: NSManagedObjectContext) ->  FetchableType
}

extension Fetchable where Self : NSManagedObject, FetchableType == Self
{
  static func createInContext(context: NSManagedObjectContext) -> FetchableType
  {
    return NSEntityDescription.insertNewObjectForEntityForName(entityName, inManagedObjectContext: context) as! FetchableType
  }
}

In each NSManagedObject subclass add the protocol Fetchable and implement the property entityName.

Now the function MyEntity.createInContext(…) will return the proper type without further type casting.



来源:https://stackoverflow.com/questions/27109268/how-can-i-create-instances-of-managed-object-subclasses-in-a-nsmanagedobject-swi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!