Can someone explain this code? I have a general idea what it does, but I just want to understand it better. Also, would this code work if we had multiple views and view controllers?
I assume this code is inside a view controller. All view controllers have a (almost certainly weak) reference to the window they’re displayed in; the window has a strong reference to the root view controller. You’re using this reference to access the managed object context used by the root view controller; so long as you don’t do anything involving creating new windows, you can probably access this resource from any screen.
You can probably use this kind of code from most view controllers. That said, from an architecture standpoint it makes your view controllers dependent on the root view controller having a managed object context, which might make it difficult to adapt for other projects.
I forgot to mentioned the code came from P. 48 in the book, inside the AppDelegate.swift file and inside the method application(_:didFinishLaunchingWithOptions: ).