Error with Swift and Core Data: fatal error: use of unimplemented initializer 'init(entity:insertIntoManagedObjectContext:)'

前端 未结 2 475
隐瞒了意图╮
隐瞒了意图╮ 2021-01-02 04:26

I have the following class that inherits from NSManagedObject:

import Foundation
import CoreData


class Note: NSManagedObject {



    @NSManag         


        
相关标签:
2条回答
  • 2021-01-02 04:30

    You must implement the following in your NSManagedObject subclass (this is the Swift 3.0 version):

    @objc
    private override init(entity: NSEntityDescription, insertInto context: NSManagedObjectContext?) {
        super.init(entity: entity, insertInto: context)
    }
    

    The answer is kind of answering it, but not really directly.

    The reasoning for this is that Swift does not inherit their supercalls designated initializers by default AND it seems as CoreData by uses this initializer when doing fetches (insert a breakpoint in the method to see). So here we "bring up" the designated initializer for CoreData to use.

    If you have NSManagedObject base classes, you must also implement this method in those.

    Credits to JSQCoreDataKit for the idea.

    0 讨论(0)
  • 2021-01-02 04:34

    This is documented behavior.

    Swift subclasses do not inherit their superclass initializers by default

    For example, following code does not even compile, because Child does not inherit init(id:String) automatically. This mechanism make sure name in Child class properly initialized.

    class Parent {
        var id:String
        init(id:String) {
            self.id = id
        }
    }
    
    class Child:Parent {
        var name:String
        init(id:String, name:String) {
            self.name = name
            super.init(id: id)
        }
    }
    
    var child1 = Child(id:"child1")
    

    If you define only convenience initializers in subclass, then it automatically inherits all of its superclass designated initializers as documented in "Automatic Initializer Inheritance" section

    0 讨论(0)
提交回复
热议问题