This video identifies the problem that makes delegates necessary, and describes and demonstrates the steps to make a delegate.
- [Instructor] Now that I've described a delegate, let's look at the demo code for an example. We'll stick with the main and dessert view controllers for now. At the very top of the dessert view controller swift file, I added a protocol, dessert view controller delegate. It looks a lot like the class under it except it has only a declaration, no code. Here I have one method, did choose dessert. That has one parameter dessert of type order item. In the properties for dessert view controller I declared a property delegate.
It is an optional value of my protocol type which I'll set to nil for now. In the dessert selection button action, I have a call to the delegate method where I've placed my dessert selection in the parameter. So this code will run a function which we don't know what it does but we'll have as its value what I'm trying to communicate outside of the controller. Head over the main view controller code. Towards the top you'll see I adopted several delegates by placing the delegate name after the subclass declaration including dessert view controller delegate.
After adopting the delegate, I flesh out the delegate in the function did choose dessert. I have the value from my parameter which is my order item which I add to my list then update the table. I've moved a value from desserts to main. Again don't forget the last step. I need to tell the dessert view controller where this fleshed out function is. In prepare for segway tell the dessert controller that the function is looking for is right here by using self.
This is one of the most common errors, forgetting to set a delegate. You'll know because you'll get an unwrapping nil fatal error when you run your code. Let's trace this one more time. Going back to dessert view controller, the dessert selection button will find us dessert selection, the delegate will run dessert and send as a parameter that dessert. That parameter goes to the protocol which says did choose dessert and looks for where that function is.
That function, because we defined it over here in prepare for segway, says that it's right here in main controller. Main controller has it here and takes that dessert order item, adds it to our order items and updates our table. Delegates are a sneaky way of moving data between controllers that shouldn't share data. I've called them sneaky but they are the most used and best way to move data between view controllers.
When you need to move data, your first thought should be setting up a delegate.
- Defining the basics of classes
- Exploring the Model-View-Controller programming pattern
- Using segues and contexts
- Moving information from a source to a destination view controller
- Writing delegates
- Moving information from a destination back to the source controller
- Using data sources in Apple factory classes