iOS Development notes: Delegate

iOS Development notes: Delegate

Delegates in five easy steps

  • Define a delegate protocol for object B.
  • Give object B an optional delegate variable. This variable should be weak.
  • Update object B to send messages to its delegate when something interesting happens, such as the user pressing the Cancel or Done buttons, or when it needs a piece of information. You write delegate?.methodName(self, ...)
  • Make object A conform to the delegate protocol. It should put the name of the protocol in its class line and implement the methods from the protocol.
  • Tell object B that object A is now its delegate. The proper place to do that is in the prepare(for: ..., send: ...) with the code: controller.delegate = self.

Example code:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "AddItem" {
        let controller = segue.destination as! AddItemViewController
        controller.delegate = self
    }
}

Data transfer between view controllers works two ways:

  • From A to B. When screen A opens screen B, A can give B data it needs. You simply make a new instance variable in B's controller. Screen A then puts an object into this property right before it makes screen B visible, usually in prepare(for: ..., send: ...).
  • From B to A. To pass data back from B to A you use a delegate.

你可能感兴趣的:(iOS Development notes: Delegate)