Search code examples
swiftcore-datainitialization

Initializer Hierarchy: Need help understanding self.init and how it points to a super class


I am trying to understand the syntax for initializers and how they work. I am reading the swift documentation and I am having a hard time understanding how they work in a specific example I am working on. I'm following a tutorial to learn about core data but I do not want to continue through the project until I understand how the initialization code works (or any other concept I do not understand).

https://docs.swift.org/swift-book/LanguageGuide/Initialization.html

Core Data: Note Entity Class

Core Data: Note Class Convenience Initializer

In the first image above I show the Note Entity Class that Core Data creates and in the second image I add a convenience init(). All the extra on the code in the extension of the Note class is my notes.

The first two comments on the extension of the Note class is what I have found out about how the entity class hierarchy which is that the super class is the NSMangedObject (super class) then the sub class is the Note entity class. To my understanding the NSMangedObject class has 3 initializers which are:

  1. init() - Default Initializer
  2. init(entity: NSEntityDescription, insertInto context: NSManagedObjectContext?) - Designated Initializer
  3. convenience init(context moc: NSManagedObjectContext) - Convenience Initializer

Then Note entity class the only thing I have is the convenience init(title: String, context: NSManagedObjectContext). For this initializer I understand how the title and creationDate are initialized but my question is on the self.init(context: context).

Question: To my understand reading the Swift documentation a convenience initializer cannot point to another convenience initializer which is what I think it's happening here?? I think that the default initializer from the Note class is pointing to the initializers from the super class of NSMangedObject. Can anyone provide me with some insight to understand what is happening.


Solution

    1. A convenience initializer must call another initializer in self. That is all it is required to do. It must do that before saying self for any other purpose.

    2. In the Node extension, the convenience initializer is doing that; it is starting out by calling self.init(context:).

    3. That is legal because Node is an NSManagedObject subclass (representing an entity), so it inherits that initializer:

      https://developer.apple.com/documentation/coredata/nsmanagedobject/1640602-init

    That's all there is to know. The fact that init(context:) is a convenience initializer is not interesting. It's an initializer of self, that's all that matters.