title: How to pass data between UIViewControllers with protocols/delegates
body: <p>In the code below I have a <code>ViewController</code>("SenderViewController"), which passes a message to the main <code>ViewController</code> when a button is tapped. What I don't fully understand is how does <code>messageData()</code> method in the main <code>ViewController</code> know when to listen for the message.</p>
  
  <p>Can someone please explain me what is triggering the <code>messageData()</code> method in the main <code>ViewController</code>?</p>
  
  <p>SenderViewController:</p>
  
  <pre><code>import UIKit  
  protocol SenderViewControllerDelegate {  
      func messageData(data: AnyObject)  
  }  
  class SenderViewController: UIViewController {  
      @IBOutlet weak var inputMessage: UITextField!  
       var delegate: SenderViewControllerDelegate?  
  
      @IBAction func sendData(sender: AnyObject) {  
          /  
          if inputMessage.text != ""{  
              self.presentingViewController!.dismissViewControllerAnimated(true, completion: nil)  
              self.delegate?.messageData(inputMessage.text!)  
          }  
      }  
  }  
  </code></pre>
  
  <p>Main ViewController:</p>
  
  <pre><code>import UIKit  
  class ViewController: UIViewController, SenderViewControllerDelegate{  
      @IBOutlet weak var showData: UILabel!  
  
      override func viewDidLoad() {  
          super.viewDidLoad()  
      }  
  
      @IBAction func goToView(sender: AnyObject) {  
          let pvc = storyboard?.instantiateViewControllerWithIdentifier("senderViewController") as! SenderViewController  
          pvc.delegate = self  
          self.presentViewController(pvc, animated:true, completion:nil)  
      }  
  
     // What triggers this method, how it know when to listen? 
      func messageData(data: AnyObject) {  
          self.showData.text = "\(data)"  
      }  
  } 
  </code></pre>
  
  <p>Thanks a lot!</p>