ankit
ankit

Reputation: 3647

Pass Data using Closures

I know that there are multiple approaches to pass data back from one controller to another like Delegates, NSNotifications. I am using another way using Closures to pass data data back. I just want to know is it safe way how I pass any data using blocks like below or should I avoid this approach.

First ViewController (where I make object of Second ViewController)

 @IBAction func push(sender: UIButton) {
        let v2Obj = storyboard?.instantiateViewControllerWithIdentifier("v2ViewController") as! v2ViewController

        v2Obj.completionBlock = {(dataReturned) -> ()in
            //Data is returned **Do anything with it **

            print(dataReturned)

        }
        navigationController?.pushViewController(v2Obj, animated: true)

    }

Second ViewController (where data is passed back to First VC)

import UIKit
typealias v2CB = (infoToReturn :NSString) ->()
class v2ViewController: UIViewController {

    var completionBlock:v2CB?
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    @IBAction func returnFirstValue(sender: UIButton) {

        guard let cb = completionBlock else {return}

        cb(infoToReturn: returnFirstValue)

    }
    @IBAction func returnSecondValue(sender: UIButton) {

        guard let cb = completionBlock else {return}

        cb(infoToReturn: returnSecondValue)

    }
}

Upvotes: 3

Views: 2554

Answers (1)

vadian
vadian

Reputation: 285082

That's a very good and reasonable approach and much better than notifications.

Looking at the evolution of Cocoa API you will notice that Apple has replaced more and more delegate API with blocks / closures over the years.

Upvotes: 4

Related Questions