Search code examples
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:

    • Dependency injection: Here is a nice post about it. This is having some data in one VC and injecting it to the next one. It's a good approach if you don't need to persist that data and other objects depend on it.

    • Delegation: You can make a VC pass data to its delegate after something happens (like a user tap, you finished downloading some data, etc).

    • Notification Center: You can send notification within the app scope and make any object (like a ViewController) to observe for specific notifications. You can send data along with a notifications.

    • Singleton design pattern: You can use singletons in Swift like this:

    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
    
    • UserDefaults: This is a storage you can use to store small pieces of data. Keep in mind that this is not a database, it will persist your data between app launches, but you should not use it to store large amounts of data.

    • CoreData: This is a a persistence framework for iOS to store data, like you would do in a server-side DB. It's not exactly a DB, because you don't access disk directly each time you read/write, CoreData loads all its content to memory to access it. You have other third party libraries to work with local persistency, like Realm.

    Hope it helps!