2

My app has the user log into their account. Then, the app accesses Parse.com to retrieve all of their information. That information is stored in a struct. I want to have that struct passed between view controllers so it can be accessed at any time in the app. Everything I've tried gives me errors. I can't declare it as an optional, or set up an identical struct in the next class. What is the solution to this?

3
  • Wrap it in a class? Why do you insist on using a struct? Commented Aug 13, 2014 at 20:58
  • 3
    You should be able to pass structs (or classes) around between view controllers without a problem. Show the code where your doing the pass and tell us what errors or uninstended behaviour your are getting when that code runs. Commented Aug 13, 2014 at 21:10
  • how to wrap it in a class? var body and some view very confusing Commented Aug 8, 2020 at 12:34

2 Answers 2

7

Use the following code to pass struct between ViewControllers

    //FirstViewController.swift

    struct GlobalStruct
    {
    var details:String;
    init()
    {
        details = "global struct";
    }
    };

    class FirstViewController: UIViewController {
    override func viewDidLoad() {
    super.viewDidLoad()
    }
@IBAction func buttonClicked()
    {
        let secondViewController = self.storyboard.instantiateViewControllerWithIdentifier("secondview") as SecondViewController
        var passData = GlobalStruct();
        passData.details = "Secret Information :)";
        secondViewController.setStructDataReference(passData); //passStruct
        self.navigationController.pushViewController(secondViewController, animated: true)
    }
   override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}


//SecondViewController.swift

class SecondViewController:UIViewController
{
    var structData:GlobalStruct;

override func viewDidLoad()
{
    println("struct data = \(self.structData.details)");
}
func setStructDataReference(structDataReference:GlobalStruct)
{
    self.structData = structDataReference;
}

    init(coder aDecoder: NSCoder!)
    {
        self.structData = GlobalStruct();
        super.init(coder: aDecoder);
    }

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

Comments

0

I would create empty arrays [Struct] on both controllers. Then in whatever action you perform before performSegue you should do:

self.arrayinmaincontroller.insert(the struct, at:0)

and pass it in func prepare(for segue: UIStoryboardSegue, sender: Any?)

Comments

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.