Reputation: 60
I have 3 view controllers in my program. Can I send more than 1 value from the first view controller to the third without segue-ing?
Or do I have to send the values to the first, the second, then the third?
Thanks in advance.
Upvotes: 0
Views: 50
Reputation: 1042
You shouldn't rely on passing values directly like you are describing because you don't even know if all of the controllers have been instantiated yet. Create a model class or struct that you can store values in and reference from all 3 controllers. Basic example of model class:
import Foundation
fileprivate let sharedModelInstance = Model()
class Model {
var basicString : String = "string"
static var sharedInstance : Model {
return sharedModelInstance
}
func setBasicString(_ str: String) {
basicString = string
}
}
Then a controller:
import UIKit
class ViewController : UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// reads 'string'
let aStr : String = Model.sharedInstance.basicString
Model.sharedInstance.setBasicString("Hello")
// Now 'Hello'
let anotherStr : String = Model.sharedInstance.basicString
}
}
This way all of your data is centralized and as long as you always refer back to your model you will never have data between controllers that is out of sync.
Upvotes: 1
Reputation: 5616
There are many ways to pass data from one view controller to another. What they all have in common is that the views are already created when the data is being passed. In your scenario, they have not all been created.
So if you're going from 1 to 2 to 3, when 1 is showing, 3 hasn't been instantiated yet. You would have to create 3, set the variable, then pass that newly created view controller 3 to view controller 2 so that 2 could then go ahead and display the already-created 3 on the screen. That whole process defeats the main purpose of your question and is much more work than the steps you're trying to avoid.
If you have one or two variables to pass, it's not such a hassle to pass to 2 then to 3. If you have a lot of data, you may want to consider putting it into one array to pass, saving it to Core Data, or even changing your data model completely.
Upvotes: 0