22

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

}
Kendall Helmstetter Gelner
  • 74,769
  • 26
  • 128
  • 150
amleszk
  • 6,192
  • 5
  • 38
  • 43

3 Answers3

29

(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.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • 1
    2¢: That generic function is a pretty good use case for the `private` keyword. – Mazyod Dec 26 '14 at 17:52
  • In Swift 2, split isn't a global function anymore. We can use classString.componentsSeparatedByString(".") instead. – Jonathan Zhan Nov 03 '15 at 10:54
  • 1
    @JonathanZhan: You are right, I'll update it. Thanks. – Martin R Nov 03 '15 at 10:56
  • 1
    @ambientlight: You are completely right. I used that in the "alternative approach" posted separately below. – Martin R Nov 18 '15 at 19:15
  • 2
    @MartinR great explanation. But I am not able to understand why func createInContext(context:NSManagedObjectContext, type : T.Type) -> T needs 'type' argument? Cant type of 'T' be inferred by the return type of caller function? #newToSwift :) – Vishal Singh Nov 28 '15 at 16:27
  • @VishalSingh: You are right, that works! – But note that a much simpler solution exists, see http://stackoverflow.com/a/33583941/1187415 below. – Martin R Nov 29 '15 at 08:42
  • @MartinR thank you for the clarification. I have seen the solution you mentioned and it works great, but I was just clearing my doubt on this one. – Vishal Singh Nov 29 '15 at 09:57
  • I believe one could potentially use [unsafeBitCast(object, self)](https://developer.apple.com/library/watchos/documentation/Swift/Reference/Swift_StandardLibrary_Functions/index.html#//apple_ref/swift/func/s:Fs13unsafeBitCastu0_rFTxMq__q_) instead of writing one's own helper func. Just a thought. – jperl Apr 17 '16 at 19:07
  • 1
    @KickimusButticus: You are right, that works here as well. But note that a simpler solution exists, see http://stackoverflow.com/a/33583941/1187415 below. – Martin R Apr 17 '16 at 20:57
11

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)
    }
}
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • It doesn't seem to work when `YourEntity` is defined in ObjC - `init` from the extension isn't called in tests - works perfectly when Swift is being used – Krzysztof Skrzynecki Jan 10 '19 at 11:42
  • Actually, it works with `YourEntity` implemented in ObjC if method argument isn't exactly the same as in overridden constructor - e.g. `convenience init(usedContext: NSManagedObjectContext)` definition and calling `let entity = YourEntity(usedContext: context)` works just fine – Krzysztof Skrzynecki Jan 10 '19 at 11:49
  • 1
    @KrzysztofSkrzynecki: Thank you for the feedback! – The `init(context:)` constructor was introduced with iOS 10, it did not exist when I wrote the initial version of this answer. – Martin R Jan 10 '19 at 12:40
4

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.

vadian
  • 274,689
  • 30
  • 353
  • 361