In the code below I have a ViewController
("SenderViewController"), which passes a message to the main ViewController
when a button is tapped. What I don't fully understand is how does messageData()
method in the main ViewController
know when to listen for the message.
Can someone please explain me what is triggering the messageData()
method in the main ViewController
?
SenderViewController:
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!)
}
}
}
Main ViewController:
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)"
}
}
Thanks a lot!
While Presenting
SenderViewController
fromMainViewController
you are setting the delegate asself
. So whenever you call the delegate method in SenderViewControllerfollowing method of
MainViewController
will act as a callbackIn
SenderViewController
:When you tap button you invoke
sendData
method. In this method you askdelegate
to invoke itsmessageData
method. Delegate property declared asSenderViewControllerDelegate
type, so you can do that (see this protocol defenition).In
ViewController
(first view controller):Before you open second view controller, in method
goToView
you seting up propertydelegate
ofSenderViewController
to 'myself', to exact instance ofViewController
, since you declared that it confirm protocolSenderViewControllerDelegate
by implementing methodmessageData
. So,ViewController
is now saved asdelegate
property inSenderViewController
, and can be used to invokemessageData
!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 themethod
is usually used for the functions of objects.) It invokes the function messageData inViewController
.Note: If you need to pass multiple data to mainViewController then use dictionary to pass them. i.e.
SenderViewController:
Main ViewController