I have the following class that inherits from NSManagedObject
:
import Foundation
import CoreData
class Note: NSManagedObject {
@NSManag
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.
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