3

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)

    }
}
2
  • Nothing wrong with this approach but do take care to understand how your closures capture values and can create retain cycles. Commented Jun 10, 2016 at 5:12
  • Yes retain cycle should be taken care Commented Jun 10, 2016 at 5:18

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

7 Comments

One thing more I want to know, The way how I pass multiple different values back is safe way or should i pass data back using methods that contains block as a parameter.
It's perfectly fine. That's one of the benefits of closures.
Thanks man!! You really lifted off confusion off my sholuders
is there an objective c equivalent?
@vnchopra Yes, blocks exist in Objective-C since macOS 10.6 Snow Leopard.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.