1

I am trying to save a boolean value across multiple views and seagues. I think using a singleton is the answer. I set up the singleton class but it still is not holding that value. This is my Singleton class that I set up.

class Singleton {
    static let instance = Singleton()
    var data: Bool = false;

    private init() { }

    func SetData(value: Bool){
        data = value
    }

    func GetData() -> Bool{
        return data
    }
}

This is where I am trying to call it. By default I set the var isOn to false. If its true it sets the user data to the Imperial system, if its false its set to Metric.

//This is the function for the button that lets the user switch between the metric system and imperial system
@IBAction func switchMeasurements(_ sender: Any) {
    var temperatureS: Float = Float(0)
    var temperatureB: Float = Float(0)
    var lakeDep: Float = Float(0)

    isOn = Singleton.instance.GetData()

    //Clicks the button, if isOn is true then we set the data to the imperial system.
    isOn = !isOn

    Singleton.instance.SetData(value: isOn)

    if isOn {
        ....}

The problem is that when they click to change to Imperial, then click and move away from that view and comeback to it, it resets isOn to false and messes with the data. I am trying to get isOn to save so when they comeback it will still be on Imperial if they selected it prior. Any tips/help would be greatly appreciated.

rmaddy
  • 298,130
  • 40
  • 468
  • 517
Dylan Kelemen
  • 173
  • 2
  • 8
  • Unrelated but please note that method and variable names should start with lowercase letters. Class and struct names start with uppercase letters. – rmaddy Nov 02 '17 at 18:39
  • Possible duplicate of [Singleton with properties in Swift 3](https://stackoverflow.com/questions/37953317/singleton-with-properties-in-swift-3) – jpetrichsr Nov 03 '17 at 18:57

1 Answers1

0

You doing it not in Swift-like manner

class Singleton {
  static var shared = Singleton()

  var data: Bool = fasle {
    get { return data }
    set { data = newValue }
  }
}

Next thing I don't understand what does it means "comeback". If you dismissed this view / poped to previous one then you the problem is that you not setting isOn state in viewDidLoad when setting subviews and so on. If you push someViewController and "comeback" to your switcher then you somewhere change shared flag state or change isOn on viewDidAppear / viewWillAppear or anywhere else. So check this variants

Hope I helped!

Mikhail Maslo
  • 536
  • 4
  • 13