fs_tigre fs_tigre - 1 year ago 77
iOS Question

Understanding passing data between ViewControllers with protocols/delegation - See code

In the code below I a ViewController(SenderViewController) passes a message to the main ViewController when a button is tapped, what don't fully understand is how does the

method in the main
knows when to listen for the message.

Can someone please explain me what is triggering the
method in the main ViewController?


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)

Main ViewController:

import UIKit
class ViewController: UIViewController, SenderViewControllerDelegate{
@IBOutlet weak var showData: UILabel!

override func 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)"

Thanks a lot!

Answer Source

Objects don't exactly listen for method calls. They sit there, waiting to invoked.

The line


From your SenderViewController is a function call. (The term method and function are pretty much interchangeable, although the method is usually used for the functions of objects.) It invokes the function messageData in ViewController.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download