Reputation: 73
I am making a app with many Views. When I am navigating from one View to another I want the data to be sent to a third view without entering the view. I know that it is a way to do this by using this code:
let nextView = self.storyboard?.instantiateViewControllerWithIdentifier("view3") as lastViewController
nextView.data = 1103
But if I do it this way and don't move to the view the data won't be saved. How can I save the data without entering it? Do I need to open it?
In the first view:
var chosenItem:Int = 0
@IBAction func buttonClicked(sender: AnyObject) {
if sender.tag == 0 {
chosenItem = 1
} else if sender.tag == 1 {
chosenItem = 2
} else if sender.tag == 2 {
chosenItem = 3
}
}
This is how my code looks now:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "toView2" {
let nextView = segue.destinationViewController as questionAgeViewController
nextView.firstAnswer = chosenItem
}
}
In the next view I send both the first item and the second. And as you understand this is not the best way to get the information. Is there a better?
Upvotes: 1
Views: 186
Reputation: 1205
I think you might be looking for a global variable. Use this code to make the variables:
struct globalVars {
static var firstVar = "Your text"
static var secondVar = Some number
static var thirdVar = Some array
}
In a other view you can access the information like this:
let globalText = globalVars.firstVar
println(globalText)
To edit the variables just use this code:
globalVars.firstVar = "The new text"
Upvotes: 2
Reputation: 14118
Create a singleton class and add properties into it, as per your requirement.
Now you can set its properties from your firstViewController and access the same from SecondViewController.
class Singleton {
class var sharedInstance: Singleton {
struct Static {
static var instance: Singleton?
static var token: dispatch_once_t = 0
}
dispatch_once(&Static.token) {
Static.instance = Singleton()
}
return Static.instance!
}
}
Singleton tutorials for Swift
Upvotes: 2