swiftstoring-data

Storing data into class


I am currently working on my first bigger project and I was wondering whether there is some way of putting data into one class and then just rewriting them or making an instance for the class. I have got a data that are being downloaded in the first ViewController and if I want to use them on all of my 5 ViewControllers, I just pass them using delegates and make a lot of duplicates. As this way is very inefficient and also messy, I would like to have them stored in one class. When I made custom class for those data, when changing to another ViewController, the data get instantly deleted.


Solution

  • You have multiple options to access the same piece of data from multiple places. The way you use fully depends on your needs. Here are a few options:

    class MySingleton {
      static let shared = MySingleton()
    
      var name = ""
    }
    
    // Assign name variable somewhere (i.e. in your first VC after downloading data)
    MySingleton.shared.name = "Bob"
    
    // In some other ViewController
    myLabel.text = MySingleton.shared.name
    

    Hope it helps!