Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
361 views
in Technique[技术] by (71.8m points)

ios - How to pass data between UIViewControllers with protocols/delegates

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

The line

self.delegate?.messageData(inputMessage.text!)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...