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?
-
Wrap it in a class? Why do you insist on using a struct?Jack– Jack2014-08-13 20:58:08 +00:00Commented Aug 13, 2014 at 20:58
-
3You 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.Alex Wayne– Alex Wayne2014-08-13 21:10:45 +00:00Commented Aug 13, 2014 at 21:10
-
how to wrap it in a class? var body and some view very confusingpete– pete2020-08-08 12:34:41 +00:00Commented Aug 8, 2020 at 12:34
Add a comment
|
2 Answers
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);
}
}