1

What is the best way to pass a variable from one ViewController to another in Swift?

I have a ViewController called DatePickerViewController.swift in which I capture the date set by the user with a UIDatePicker object.

I then need to access the date variable from another view controller.

Should this be done by passing data forward using Segue's or should I be creating a global variable to access from various ViewControllers?

After much research I can't figure this one out. An explanation of the best way to do this would be greatly appreciated.

Many thanks.

Community
  • 1
  • 1
BuiltBySam
  • 11
  • 1
  • 4

3 Answers3

1

Well, it actually depends from your needs. If you just need to pass one piece of data from a view controller to another, you can simply define a property in your destination view controller and set it in your source view controller before performing the segue (using the func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) method).

On the other hand, if you have to pass massive data from multiple view controllers, you should consider the idea of creating a Data Model class and storing and retrieving all the information you need from there.

Dree
  • 702
  • 9
  • 29
0

You can access variables and arrays in multiple ViewControllers through NSUserDefaults.

Saving data to NSUserDefaults:

Before we read or write data from NSUserDefaults, we must first get a reference to the NSUserDefaults class.

let prefs = NSUserDefaults.standardUserDefaults()

Once we have the reference saved to a constant, we can write data to it. You will be defining both the value and the key name to store the data.

prefs.setValue("Berlin", forKey: "userCity")

Reading data from NSUserDefaults:

Reading data is similar to writing it. Again, let’s get a reference to the NSUserDefaults class and then we can query a key for a value.

let prefs = NSUserDefaults.standardUserDefaults()
if let city = prefs.stringForKey("userCity"){
println("The user has a city defined: " + city) 
}else{ 
prefs.setValue("Berlin", forKey: "userCity")  
}
bearacuda13
  • 1,779
  • 3
  • 24
  • 32
Ammar
  • 105
  • 1
  • 10
0

Refer and use the following code in your project

in FirstViewController

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) 
{
     if segue.identifier == "goNextPage"
     {
        var destinationVC = segue.destinationViewController as? SecondViewController

        destinationVC?.dataFromPreviousViewController = "Success"

     }
}

in SecondViewController

var dataFromPreviousViewController = ""  

override func viewDidLoad() 

{
    super.viewDidLoad()

    // Do any additional setup after loading the view.

    labelGetText.text = dataFromPreviousViewController

    println(labelGetText.text)

}

Important : First of all you have to set segue as Show and give identifier name as goNextPage in StoryboardSegue(whatever you want give here)

user3182143
  • 9,459
  • 3
  • 32
  • 39