I have developed an app that gets a lot of JSON data from server and shows on different VCs.What I did was getting data and setting data to static variables, so I can access data in all my app.
Now I noticed that I could have used CoreData
or maybe UserDefaults
instead of Static variables
.
My question is "What is the best practice for this type of apps and why exactly?"
NOTE: The app doesn't need to work offline and save data for showing in offline mode.
For "small" data like key : value it's best to use UserDefaults. If you have more to store, use CoreDara as this is basically a SQLite database.
Basically I am flowing three option :
Global variable : I need to define Globally struct :
now I can use simply call the global variable from anywhere in my project :
UserDefaults
it is using for data store but which is not sensitive data :
keyChain it is using for data store but which is sensitive data like username, password or tokens.
Save and retrieve value via KeyChain swift
but I am personally recommend to flow this blog that is published by apple
Apple iOS Data Storage Guidelines
more interested read this question thread :
How to save local data in a Swift app?
Discussion:
"What is the best practice for this type of apps and why exactly?" is a very good question. It would help if you described what type of app you are developing.
Since you only seem to need/want the data while the app is running then I guess the best way is to keep it in memory on some singleton or static variables which you are already doing.
But if you don't want to store your data after the app is relaunched then you might want your data to expire after some duration since app may be opened for a very long time.
Then the question is how you want to receive your data in runtime. Assume you have cached data and you wish to refresh the data anyway. Then you may design your data management so your closure to fetch items may be call multiple times. Assume having something like this:
Then let's say you want to show these users in some table view you would do something like:
This will design your user interface part of the data fetching but has nothing to do with where and how your data is stored. For instance
MyCache
should still chose weather the cached response is still valid or outdated. And it isMyCache
which decides to either store data into some database or only in-memory.Some storing procedures:
To keep the design in previous snippets you may have a static class
MyCache
which has an string enumeration for stored types. It then has a static dictionary[String: Any]
which contains cached data so a fetch method looks something likeThe insertion is pretty similar then.
To add date (or any other data in there) you may define it as
[String: [String: Any]]
and use static keys so then your data would becacheDictionary[type]["date"] as? Date
and data ascacheDictionary[type]["data"]
.You may then expand your cache to for instance use user defaults like:
This is for storing direct JSON data or objects. Same can be applied for storing data (serializing it with
JSONSerializer
) into files. You could create a base path in temporary directory or in library then use file names bytype
. Temporary directory may be cleared by the system which you might want and library directory will be persistent.Then there is database:
The database is a whole other story. It makes no sense to apply a database into the same procedure as above because it is an overkill and you use no benefits of the database at all.
For database you would create models for each of your responses and insert the data into database then notify your UI controllers to update. That means callbacks are not the best practice but rather delegates. You would have for instance
DatabaseManager
and on view did appear you would callDatabaseManager.shared.delegate = self
thenUsers.fetchNewUsers()
and waited for the delegate to trigger. Then on delegate you would fetch objects from database or create a fetch result controller...There probably very many other ways but I hope this will give you some idea about how to store data when to use which.
You can create data model class to store temporary data from JSON response.
Example of Data Model class : -
Simple way to create data model class : - jsoncafe.com
You should not store data to UserDefaults, user defaults is just a key value based file which is mostly used to store some data about user, for example :
You should not use keychain either since keychain is encrypted container where u store critic data about user, for example : password.
You don't need to use database
My opinion is that you should not use global variables, mainly I try to make viewController data specific for itself, the data should not be accessed from anywhere in your project. When to use global variables in Swift
Mostly I make service protocols with implementations for specific view controllers. Anyways, each controller should have its own part of data for example
Once you load data from your API, the data will be there, until you close your app.
You can always make another class which will contain this data and maybe predicates for cleaner approach for example :
I use similar approach, instead of saving data in my service classes (business logic), I got repositories which I use to get data from database. Since you don't have any database this approach is okay.
and then instead of
you can use
Hope it helps, Best regards!