Tutorial 2: When to override init( ) and when not

I’m redoing the Checklist app and trying to better understand how to work with persistent memory and initialization. One thing that I’m having trouble understanding is when you need a default init() to go along with a custom init with multiple parameters. In the ChecklistItem, we created an initializer of: required init?(coder aDecoder: NSCoder) and once that code was added, another init of override init( ) was necessary to keep the compiler happy.

(1) Is this because we are telling the compiler, this is how you initialize a Checklist object that comes from NSCoder, but I need to also tell you how to initialize a Checklist object when it’s created by itself? And the default init ( ) simply runs the initializer from its superclass (NSObject)?

(2) Why does the ChecklistViewController NOT require that default init ( ) function? We also have a custom initializer for working with NSCoder in that file, but no other.

(3) In the ChecklistViewController, we have the variable, var items: [ChecklistItem], I can see how this would be initialized in that NSCoder initializer method. But when there isn’t an items object (i.e. there’s no Checklist.plist created yet), where does the initialization take place?

Thanks for your help!

We want to create Checklist objects in two ways:

  • a new, empty, Checklist – this uses the init() method
  • when loading existing Checklists as the app starts – this uses the init(coder) method

Both inits serve a different purpose.

ChecklistViewController is created by UIKit as it loads the storyboard. It uses init(coder) for that. If you want to create a view controller that is not on a storyboard, you can use init() or init(nibName).

That makes sense. I think writing out my question helped a lot, and you answered exactly what I didn’t understand. Just to confirm:

Custom objects have an init method, but when overriding how to load them from coder, you also need to include a init method for when it’s not being loaded from coder.

Table Views are always using init(coder) when loaded from storyboards.

Thanks again for your help. I’m really enjoying the tutorials.